本文實例講述了Java SHA-256加密的兩種實現方法。分享給大家供大家參考,具體如下:
最近在做注冊的一個功能,密碼要進行加密,一開始想用MD5加密,但是聽說被破解了已經,於是想玩玩SHA-256加密。學習了下,總結兩種方法供后面參考:
1、利用Apache的工具類實現加密:
maven:
1
2
3
4
5
|
<
dependency
>
<
groupId
>commons-codec</
groupId
>
<
artifactId
>commons-codec</
artifactId
>
<
version
>${common-codec.version}</
version
>
</
dependency
>
|
實現代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
/***
* 利用Apache的工具類實現SHA-256加密
* @param str 加密后的報文
* @return
*/
public
static
String getSHA256Str(String str){
MessageDigest messageDigest;
String encdeStr =
""
;
try
{
messageDigest = MessageDigest.getInstance(
"SHA-256"
);
byte
[] hash = messageDigest.digest(str.getBytes(
"UTF-8"
));
encdeStr = Hex.encodeHexString(hash);
}
catch
(NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch
(UnsupportedEncodingException e) {
e.printStackTrace();
}
return
encdeStr;
}
|
2、利用Java自帶的實現加密:
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
|
/**
* 利用java原生的摘要實現SHA256加密
* @param str 加密后的報文
* @return
*/
public
static
String getSHA256StrJava(String str){
MessageDigest messageDigest;
String encodeStr =
""
;
try
{
messageDigest = MessageDigest.getInstance(
"SHA-256"
);
messageDigest.update(str.getBytes(
"UTF-8"
));
encodeStr = byte2Hex(messageDigest.digest());
}
catch
(NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch
(UnsupportedEncodingException e) {
e.printStackTrace();
}
return
encodeStr;
}
/**
* 將byte轉為16進制
* @param bytes
* @return
*/
private
static
String byte2Hex(
byte
[] bytes){
StringBuffer stringBuffer =
new
StringBuffer();
String temp =
null
;
for
(
int
i=
0
;i<bytes.length;i++){
temp = Integer.toHexString(bytes[i] &
0xFF
);
if
(temp.length()==
1
){
//1得到一位的進行補0操作
stringBuffer.append(
"0"
);
}
stringBuffer.append(temp);
}
return
stringBuffer.toString();
}
|