md5 加密
IOS Objective-C 版本
一般是调用IOS系统自带的方法
#import <CommonCrypto/CommonDigest.h> // md5需要引用这个文件
// md5 32位 加密
+ (NSString *) MD5:(NSString *) string {
const char *cStr = [string UTF8String];
unsigned char result[16];
CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
NSString *output = [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]
];
NSLog(@"MD5 %@", output);
return output;
}
// 优化下,变成这样
+ (NSString *) MD5:(NSString *) string {
const char *cStr = [string UTF8String];
unsigned char digest[16];
CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x", digest[i]];
NSLog(@"MD5 %@", output);
return output;
}
参看这里
Android 版本
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public static String MD5(String sourceStr) {
String result = "";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(sourceStr.getBytes());
byte b[] = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
result = buf.toString();
} catch (NoSuchAlgorithmException e) {
System.out.println(e);
}
return result;
}
测试对照地址
http://tool.chinaz.com/Tools/MD5.aspx