SecurityTool.java
3.25 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package com.xkl.security;
import java.security.MessageDigest;
import java.util.Random;
/**
* Created by win7 on 2016/11/7.
* 首先将用户输入的原始密码进行md5加密;
* 将用户账号和加密盐(用户注册和修改时生成的随机字符串)进行sha1加密;
* 将sha1加密后的密文和原始密码加密后的密文一起进行md5加密,这样就得到了最终的加密密码
*/
public class SecurityTool {
private static final String ALGORITHM = "SHA1";
public static final String ALGORITHM_MD5 = "MD5";
private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f' };
/**
* 生成SALT的数组(86)
*/
private static final String[] SALT_ARR = { "a", "b", "c", "d", "e", "f", "g", "h",
"i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
"v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H",
"I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
"V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8",
"9", "0"};
/**
* SALT长度
*/
private static final int SALT_LENGTH = 16;
/**
* 生成16为随机salt
* @return
*/
public static String genSalt() {
StringBuffer result = new StringBuffer();
Random r = new Random();
int temp = 0;
for (int i = 0; i < SALT_LENGTH; i++) {
temp = r.nextInt(SALT_ARR.length);
result.append(SALT_ARR[temp]);
}
return result.toString();
}
/**
* encode string
*
* @param algorithm
* @param str
* @return String
*/
public static String encode(String algorithm, String str) {
if (str == null) {
return null;
}
try {
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
messageDigest.update(str.getBytes());
return getFormattedText(messageDigest.digest());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Takes the raw bytes from the digest and formats them correct.
*
* @param bytes
* the raw bytes from the digest.
* @return the formatted bytes.
*/
private static String getFormattedText(byte[] bytes) {
int len = bytes.length;
StringBuilder buf = new StringBuilder(len * 2);
// 把密文转换成十六进制的字符串形式
for (int j = 0; j < len; j++) {
buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
}
return buf.toString();
}
public static String getPassword(String account, String origalPassword, String salt) {
// 将原始密码加密成md5
String md5pass = encode("MD5",origalPassword);
//用户在数据库中存储的数据为:md5(sha1(account + salt) + md5pass)
String encodePass = encode("MD5", encode("SHA1",account + salt) + md5pass);
return encodePass;
}
public static void main(String[] args) {
String salt=genSalt();
System.out.println(salt);
System.out.println(getPassword("admin", "admin",salt));
}
}