简体   繁体   English

在IOS和Windows中MD5哈希是相同的,但在java中则不同

[英]MD5 hashing is same in IOS and windows but different in java

I am getting the same value for IOS and Winows md5 hashing but in the case of java i am getting a different value, 我得到了IOS和Winows md5散列的相同值,但在java的情况下我获得了不同的值,

IOS code for md5 hashing 用于md5散列的IOS代码

- (NSString*)md5HexDigest:(NSString*)input
{
    NSData *data = [input dataUsingEncoding:NSUTF16LittleEndianStringEncoding];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5([data bytes], (CC_LONG)[data length], result);

    NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];
    for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
        [ret appendFormat:@"%02x",result[i]];
    }
    return ret;
}

Windows Code for md5 hashing 用于md5散列的Windows代码

private static string GetMD5(string text)
        {
            UnicodeEncoding UE = new UnicodeEncoding();
            byte[] hashValue;
            byte[] message = UE.GetBytes(text);

            MD5 hashString = new MD5CryptoServiceProvider();
            string hex = "";

            hashValue = hashString.ComputeHash(message);
            foreach (byte x in hashValue)
            {
                hex += String.Format("{0:x2}", x);
            }
            return hex;
        }

Java Code for md5 hasing: Tried with UTF-8,16,32 , but not maching with the IOS and Windows md5 hasing的Java代码:尝试使用UTF-8,16,32,但没有使用IOS和Windows

 public String MD5(String md5)  {
   try {

       String dat1 = md5.trim();
        java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
        byte[] array = md.digest(dat1.getBytes("UTF-16"));
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; ++i) {
          sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
       }
        System.out.println("Digest(in hex format):: " + sb.toString());
        return sb.toString();
    } catch (java.security.NoSuchAlgorithmException e) {
    }
   catch(UnsupportedEncodingException e)
   {
   }
    return null;
}

thanks 谢谢

Here a short overview what getBytes() returns related to the specified character set (all credits go to @Kayaman) 这里简要概述getBytes()返回与指定字符集相关的内容(所有信用转到@Kayaman)

"123".getBytes("UTF-8")   :                31 32 33 
"123".getBytes("UTF-16")  : FE FF 00 31 00 32 00 33 
"123".getBytes("UTF-16LE"):       31 00 32 00 33 00 
"123".getBytes("UTF-16BE"):       00 31 00 32 00 33 

It shows that the BOM is added only if the endianness is not specified. 它显示仅在未指定字节顺序时才添加BOM。 Then it depends on your architecture if LE or BE is used. 如果使用LEBE则取决于您的架构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM