簡體   English   中英

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

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

我得到了IOS和Winows md5散列的相同值,但在java的情況下我獲得了不同的值,

用於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;
}

用於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;
        }

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;
}

謝謝

這里簡要概述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 

它顯示僅在未指定字節順序時才添加BOM。 如果使用LEBE則取決於您的架構。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM