Java端代码如下:
第一种方法:
public class test {
public final static String MD5(String s) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
try {
byte[] strTemp = s.getBytes();
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(strTemp);
byte[] md = mdTemp.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
return null;
}
}
//测试
public static void main(String[] args) {
String testStr = "1";
String resultStr = MD5(testStr);
System.out.println(resultStr);
}
}
第2中方法:
public static String md5(String str) {
String digest = null;
StringBuffer buffer = new StringBuffer();
try {
MessageDigest digester = MessageDigest.getInstance("md5");
byte[] digestArray = digester.digest(str.getBytes());
for (int i = 0; i < digestArray.length; i++) {
buffer.append(String.format("%02x", digestArray[i]));
}
digest = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return digest;
}
iOS端代码如下:
+(NSString *)stringToMD5:(NSString *)inputStr{
const charchar *cStr = [inputStr UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(cStr, strlen(cStr), result);
NSString *resultStr = [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
];
return [resultStr lowercaseString];
}
这样就可以达到Java与iOS加密后的结果一致!!!
网友评论