我在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的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
被使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句