在Android应用当中,经常需要传送一些设备信息给后台,一般这些信息都要经过MD5编码,下面介绍一下MD5编码功能,直接上代码:
1 public static String md5(String s) { 2 try { 3 // Create MD5 Hash 4 MessageDigest digest = java.security.MessageDigest 5 .getInstance("MD5"); 6 digest.update(s.getBytes()); 7 byte messageDigest[] = digest.digest(); 8 9 return toHexString(messageDigest); 10 } catch (NoSuchAlgorithmException e) { 11 e.printStackTrace(); 12 } 13 14 return ""; 15 } 16 17 private static final char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5', 18 '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; 19 20 public static String toHexString(byte[] b) { // String to byte 21 StringBuilder sb = new StringBuilder(b.length * 2); 22 for (int i = 0; i < b.length; i++) { 23 sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]); 24 sb.append(HEX_DIGITS[b[i] & 0x0f]); 25 } 26 return sb.toString(); 27 }