Java版MD5加密算法

 

调用方法为:

 

Encript.md5("www.young-sun.com");

 

 

 

View Code
 1 package com.youngsun.lbt; 
2
3 import java.security.MessageDigest;
4
5 publicclass Encript {
6 //十六进制下数字到字符的映射数组
7 privatefinalstatic String[] hexDigits = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
8 /**把inputString加密*/
9 publicstatic String md5(String inputStr){
10 return encodeByMD5(inputStr);
11 }
12 /**
13 * 验证输入的密码是否正确
14 * @param password 真正的密码(加密后的真密码)
15 * @param inputString 输入的字符串
16 * @return验证结果,boolean类型
17 */
18 publicstaticboolean authenticatePassword(String password,String inputString){
19 if(password.equals(encodeByMD5(inputString))){
20 returntrue;
21 }else{
22 returnfalse;
23 }
24 }
25 /**对字符串进行MD5编码*/
26 privatestatic String encodeByMD5(String originString){
27 if (originString!=null) {
28 try {
29 //创建具有指定算法名称的信息摘要
30 MessageDigest md5 = MessageDigest.getInstance("MD5");
31 //使用指定的字节数组对摘要进行最后更新,然后完成摘要计算
32 byte[] results = md5.digest(originString.getBytes());
33 //将得到的字节数组变成字符串返回
34 String result = byteArrayToHexString(results);
35 return result;
36 } catch (Exception e) {
37 e.printStackTrace();
38 }
39 }
40 returnnull;
41 }
42 /**
43 * 轮换字节数组为十六进制字符串
44 * @param b 字节数组
45 * @return十六进制字符串
46 */
47 privatestatic String byteArrayToHexString(byte[] b){
48 StringBuffer resultSb = new StringBuffer();
49 for(int i=0;i<b.length;i++){
50 resultSb.append(byteToHexString(b[i]));
51 }
52 return resultSb.toString();
53 }
54 //将一个字节转化成十六进制形式的字符串
55 privatestatic String byteToHexString(byte b){
56 int n = b;
57 if(n<0)
58 n=256+n;
59 int d1 = n/16;
60 int d2 = n%16;
61 return hexDigits[d1] + hexDigits[d2];
62 }
63 }


 

posted @ 2011-10-05 23:59  濤叔  阅读(469)  评论(0编辑  收藏  举报