MD5加盐算法

原文链接
http://blog.csdn.net/zhanglianhai555/article/details/47081001?utm_source=tuicool&utm_medium=referral

完整代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.cloudcof.cofserver.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;


public class MD5WithSalt {

public static String generate(String password){
Random r = new Random();
StringBuilder sb = new StringBuilder(16);

//拼接两个在区间[0,99999999)内的整数,不足16位补0
sb.append(r.nextInt(99999999)).append(r.nextInt(99999999));
int len = sb.length();
if(len<16){
for (int i = 0; i < 16-len; i++) {
sb.append("0");
}
}

String salt = sb.toString();
password = md5Hex(password+salt);

char[] cs = new char[48];
//形如_o_ _o_ _o_(_代表MD5消息摘要,o代表salt)
//MD5是32位,salt是16位
for(int i=0;i<48;i+=3){
cs[i] = password.charAt(i/3*2);
cs[i+1] = salt.charAt(i/3);
cs[i+2] = password.charAt(i/3*2+1);
}

return new String(cs);
}

public static boolean verify(String password,String md5WithSalt){
char[] md5Chars = new char[32];
char[] saltChars = new char[16];
for(int i=0;i<48;i+=3){
//每经过一次循环,md5Chars获得两个值并设置。
md5Chars[i/3*2] = md5WithSalt.charAt(i);
saltChars[i/3] = md5WithSalt.charAt(i+1);
md5Chars[i/3*2+1] = md5WithSalt.charAt(i+2);
}
String salt = new String(saltChars);
return md5Hex(password+salt).equals(new String(md5Chars));
}

public static String md5Hex(String src){
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] bs = md5.digest(src.getBytes());
return new String(new Hex().encode(bs));
}

// public static void main(String[] args) {
// String password = generate("admin");
// System.out.println(password);
// System.out.println(verify("admin", password));
// }
}

//类的职能:二进制转换成十六进制
class Hex{
String encode(byte[] b){
String hs = "";
String stmp = "";
for (int i = 0; i < b.length; i++) {
stmp = (java.lang.Integer.toHexString(b[i]&0XFF));
if (stmp.length() == 1) {
hs = hs+"0"+stmp;
}else{
hs = hs+stmp;
}
}

return hs.toUpperCase();
}
}

热评文章