forked from morethink/algorithm
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSHAUtil.java
More file actions
115 lines (103 loc) · 2.94 KB
/
SHAUtil.java
File metadata and controls
115 lines (103 loc) · 2.94 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package algorithm.security;
/**
* @author 李文浩
* @version 2017/3/26.
*/
import com.google.common.base.Strings;
import java.security.MessageDigest;
/**
* SHA的全称是Secure Hash Algorithm,即安全散列算法
* Created by fangzhipeng on 2017/3/21.
*/
public class SHAUtil {
/**
* 定义加密方式
*/
private final static String KEY_SHA = "SHA";
private final static String KEY_SHA1 = "SHA-1";
/**
* 全局数组
*/
private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
/**
* 构造函数
*/
public SHAUtil() {
}
/**
* SHA 加密
*
* @param data 需要加密的字节数组
* @return 加密之后的字节数组
* @throws Exception
*/
public static byte[] encryptSHA(byte[] data) throws Exception {
// 创建具有指定算法名称的信息摘要
// MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
MessageDigest sha = MessageDigest.getInstance(KEY_SHA1);
// 使用指定的字节数组对摘要进行最后更新
sha.update(data);
// 完成摘要计算并返回
return sha.digest();
}
/**
* SHA 加密
*
* @param data 需要加密的字符串
* @return 加密之后的字符串
* @throws Exception
*/
public static String encryptSHA(String data) throws Exception {
// 验证传入的字符串
if (Strings.isNullOrEmpty(data)) {
return "";
}
// 创建具有指定算法名称的信息摘要
MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
// 使用指定的字节数组对摘要进行最后更新
sha.update(data.getBytes());
// 完成摘要计算
byte[] bytes = sha.digest();
// 将得到的字节数组变成字符串返回
return byteArrayToHexString(bytes);
}
/**
* 将一个字节转化成十六进制形式的字符串
*
* @param b 字节数组
* @return 字符串
*/
private static String byteToHexString(byte b) {
int ret = b;
//System.out.println("ret = " + ret);
if (ret < 0) {
ret += 256;
}
int m = ret / 16;
int n = ret % 16;
return hexDigits[m] + hexDigits[n];
}
/**
* 转换字节数组为十六进制字符串
*
* @param bytes 字节数组
* @return 十六进制字符串
*/
private static String byteArrayToHexString(byte[] bytes) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
sb.append(byteToHexString(bytes[i]));
}
return sb.toString();
}
/**
* 测试方法
*
* @param args
*/
public static void main(String[] args) throws Exception {
String key = "123";
System.out.println(encryptSHA(key));
}
}