1 package com.jdk7.chapter5; 2 3 import java.security.MessageDigest; 4 import java.security.NoSuchAlgorithmException; 5 6 public class PassWord { 7 //该字符串数组元素与转换后的十六进制数一一对应 8 private static String[] nums = new String[] {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", 9 "b", "c", "d", "e", "f"}; 10 11 /** 12 * 1.将加密字符串分解为byte[] 13 * 2.调用java.security.MessageDigest的静态方法获取对象,再调用实例方法digest将分解的byte[]生成对应的长度为16的byte[] 14 * 3.将长度为16的byte[]转换为十六进制 15 * 4.将数组中每个byte类型值转换为十六进制,从而实现byte[]全部转换为十六进制 16 * 5.将转换后的十六进制字符串拼接 17 * @param str 18 * @return 19 * @throws NoSuchAlgorithmException 20 */ 21 public static String createPassword(String str) throws NoSuchAlgorithmException{ 22 byte[] b = str.getBytes(); 23 for(int i=0;i<b.length;i++){ 24 System.out.print(b[i]+" "); 25 } 26 System.out.println(); 27 byte[] bt = MessageDigest.getInstance("MD5").digest(b); 28 29 for(int i=0;i<bt.length;i++){ 30 System.out.print(bt[i]+" "); 31 } 32 System.out.println(); 33 34 String results = byteArrayToHexString(bt).toUpperCase(); 35 return results; 36 } 37 38 private static String byteArrayToHexString(byte[] bt) { 39 StringBuffer sb = new StringBuffer(); 40 for(int i=0;i<bt.length;i++){ 41 sb.append(byteToHexString(bt[i])); 42 } 43 return sb.toString(); 44 } 45 46 /** 47 * byte和int类型间相互转换,int范围基于[-256,256] 48 * int类型强制转换为byte时,如int i值大于127则自减256; 如果范围为int i为[0,127],则取i对应的值 ; 如果int i在[-256,-128)则自加256 ;如果int i为[-128,0]则取i对应的值 49 * 续上:byte再转换为int时,如byte b小于等于零则自加256; 如果范围为int i为(0,127] 50 * @param b 51 * @return 52 */ 53 private static String byteToHexString(byte b) { 54 int n = b; 55 //该规则主要是int类型转换为byte类型规则的逆向 56 if(n<=0){ 57 n = n+256; 58 } 59 byte b1 = (byte)n; 60 int d1 = n / 16; 61 int d2 = n % 16; 62 return nums[d1]+nums[d2]; 63 } 64 65 public static void main(String[] args) throws NoSuchAlgorithmException { 66 System.out.println(PassWord.createPassword("celineluo")); 67 System.out.println(PassWord.createPassword("celineluo1")); 68 } 69 } 70 71 72 执行结果: 73 99 101 108 105 110 101 108 117 111 74 -75 -39 -40 -73 53 113 -16 -97 26 104 -34 -2 105 13 -120 -120 75 B5D9D8B73571F09F1A68DEFE690D8888 76 99 101 108 105 110 101 108 117 111 49 77 53 -97 -35 83 102 21 53 -52 33 76 67 -117 -28 125 -80 -34 78 359FDD53661535CC214C438BE47DB0DE