1 package com.jqqd.test;
2
3 import java.security.MessageDigest;
4
5 public class Password {
6
7 private final static String[] hexDigits = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
8 //十六进制下数字到字符的映射数组
9
10 /**把inputString加密*/
11 public static String createPassword(String inputString){
12 return encodeByMD5(inputString);
13 }
14
15 /**
16 * 验证输入的密码是否正确
17 * @param password 真正的密码(加密后的真密码)
18 * @param inputString 输入的字符串
19 * @return 验证结果,boolean类型
20 */
21 public static boolean authenticatePassword(String password,String inputString){
22 if(password.equals(encodeByMD5(inputString))){
23 return true;
24 }else{
25 return false;
26 }
27 }
28
29 /**对字符串进行MD5编码*/
30 private static String encodeByMD5(String originString){
31 if(originString != null){
32 try{
33 //创建具有指定算法名称的信息摘要
34 MessageDigest md = MessageDigest.getInstance("MD5");
35 //使用指定的字节数组对摘要进行最后更新,然后完成摘要计算
36 byte[] results = md.digest(originString.getBytes());
37 //将得到的字节数组变成字符串返回
38 String resultString = byteArrayToHexString(results);
39 return resultString.toUpperCase();
40 }catch(Exception ex){
41 ex.printStackTrace();
42 }
43 }
44 return null;
45 }
46
47 /**
48 * 轮换字节数组为十六进制字符串
49 * @param b 字节数组
50 * @return 十六进制字符串
51 */
52 private static String byteArrayToHexString(byte[] b){
53 StringBuffer resultSb = new StringBuffer();
54 for(int i=0;i<b.length;i++){
55 resultSb.append(byteToHexString(b[i]));
56 }
57 return resultSb.toString();
58 }
59
60 /**
61 * 将一个字节转化成十六进制形式的字符串
62 */
63 private static String byteToHexString(byte b){
64 int n = b;
65 if(n<0)
66 n=256+n;
67 int d1 = n/16;
68 int d2 = n%16;
69 return hexDigits[d1] + hexDigits[d2];
70 }
71
72 public static void main(String[] args){
73 String password = Password.createPassword("yaowenchao");
74 System.out.println("对yaowenchao用MD5摘要后的字符串:"+password);
75 String inputString = "tianshi0253";
76 System.out.println("tianshi0253与密码匹配?"+Password.authenticatePassword(password, inputString));
77 inputString = "yaowenchao";
78 System.out.println("yaowenchao与密码匹配?"+Password.authenticatePassword(password, inputString));
79 }
80
81 }