iOS MD5加密算法
1 #import <CommonCrypto/CommonDigest.h> // Need to import for CC_MD5 access 2 3 4 - (NSString *)md5:(NSString *)str 5 { 6 const char *cStr = [str UTF8String]; 7 unsigned char result[16]; 8 CC_MD5(cStr, strlen(cStr), result); // This is the md5 call 9 return [NSString stringWithFormat: 10 @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", 11 result[0], result[1], result[2], result[3], 12 result[4], result[5], result[6], result[7], 13 result[8], result[9], result[10], result[11], 14 result[12], result[13], result[14], result[15] 15 ]; 16 }
对应的java的加密算法
1 package com.hiveview.phone.util; 2 3 import java.security.MessageDigest; 4 5 6 public class Md5Utils { 7 8 private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5","6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; 9 10 11 /** 12 13 * 转换字节数组为16进制字串 14 15 * 16 * @param b 17 18 * 字节数组 19 20 * @return 16进制字串 21 22 */ 23 24 public static String byteArrayToHexString(byte[] b) { 25 26 StringBuffer resultSb = new StringBuffer(); 27 28 for (int i = 0; i < b.length; i++) 29 { 30 31 resultSb.append(byteToHexString(b[i])); 32 33 } 34 35 return resultSb.toString(); 36 37 } 38 39 40 private static String byteToHexString(byte b) { 41 42 int n = b; 43 44 if (n < 0) 45 46 n = 256 + n; 47 48 int d1 = n / 16; 49 50 int d2 = n % 16; 51 52 return hexDigits[d1] + hexDigits[d2]; 53 54 } 55 56 57 public static String MD5Encode(String origin) { 58 59 String resultString = null; 60 61 62 try { 63 64 resultString = new String(origin); 65 66 MessageDigest md = MessageDigest.getInstance("MD5"); 67 68 resultString = byteArrayToHexString(md.digest(resultString.getBytes())); 69 70 } catch (Exception ex) { 71 72 ex.printStackTrace(); 73 } 74 75 return resultString; 76 77 } 78 79 }