java - MD5 hashing在IOS和windows中相同,在java中不同

标签 java c# ios hash md5

对于 IOS 和 Windows 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。那么要看你的架构是用LE还是BE

关于java - MD5 hashing在IOS和windows中相同,在java中不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29234950/

相关文章:

java - 向DNS服务器请求记录并检查权威性

c# - 检测窗口何时关闭并在 C# 中传递窗口的路径

ios - 在 iOS 和 tvOS 的两个嵌入式框架之间共享模块名称

iOS 崩溃 : libswiftAssetsLibrary. dylib 未加载

java - 通过 Android 客户端连接到 WCF 服务

java - mySql-java 简单搜索控制台应用程序

c# - Linq 到 NHibernate : sum of sums

ios - 字符串字符(标记)计数不正确

java - Kinesis 工作人员错误 : Caught exception when initializing LeaseCoordinator

c# - 解析器错误消息 : The file '/TestSite/Default.aspx.cs' does not exist