做过网站的人都知道用户密码必须经过加密的,其中用的最普遍的就是MD5加密了.但是随着彩虹桥技术的兴起,MD5加密已经不再安全.今天小编就要介绍一种全新的,安全的加密算法:PBKDF2
PBKDF2算法通过多次hash来对密码进行加密。原理是通过password和salt进行hash,然后将结果作为salt在与password进行hash,多次重复此过程,生成最终的密文。此过程可能达到上千次,逆向破解的难度太大,破解一个密码的时间可能需要几百年,所以PBKDF2算法是安全的.
话不多说,上代码!!!
encode()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21/** * PBKDF2加密 * @author knight * @param plain 明文 * @return String 密文 */ public static String encode(String plain) { //1.生成随机盐salt byte[] salt = EncryptUtil.generateSalt(32); //2.随机盐HEX加密 String encodeHex = EncryptUtil.encodeHex(salt); //3.明文和随机盐一起SHA1运算1024次 byte[] sha1 = EncryptUtil.sha1(plain.getBytes(), salt, 1024); //4.对运算结果进行HEX加密 String ciperText = EncryptUtil.encodeHex(sha1); //4.加密后的随机盐和加密后的明文生成密文 String finalText=encodeHex+ciperText; return finalText; }
generateSalt()
/**
* 生成随机的Byte[]作为salt.
*
* @param numBytes byte数组的大小
*/
public static byte[] generateSalt(int numBytes) {
Validate.isTrue(numBytes > 0, “numBytes argument must be a positive integer (1 or larger)”, numBytes);
byte[] bytes = new byte[numBytes];
random.nextBytes(bytes);
return bytes;
}
encodeHex()
/**
* Hex编码.
*/
public static String encodeHex(byte[] input) {
return new String(Hex.encodeHex(input));
}
sha1()
/**
* 对输入字符串进行sha1散列.
*/
public static byte[] sha1(byte[] input) {
return digest(input, SHA1, null, 1);
}
decode()
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/** * PBKDF2解密 * @param plain 明文 * @param ciper 密文 * @return flag 对比结果 */ public static boolean decode(String plain,String ciper) { boolean flag=false; //1.截取随机盐 String saltHex = ciper.substring(0, 32*2); //2.随机盐解密 byte[] salt = EncryptUtil.decodeHex(saltHex); //3.明文和随机盐一起SHA1运算1024次 byte[] sha1 = EncryptUtil.sha1(plain.getBytes(), salt, 1024); //4.对运算结果进行HEX加密 String ciperText = EncryptUtil.encodeHex(sha1); //5.生成密文 String finalCiper=saltHex+ciperText; if(finalCiper.equals(ciper)) { flag=true; } return flag; }
main方法
1
2
3
4
5
6
7
8
9public static void main(String[] args) { String plain="admin"; String ciper=encode(plain); System.out.println(ciper); System.out.println(decode(plain, ciper)); }
运行结果:
65ab8cc6b61f03a5953c6d020b6fc95c8719717147a941b66fc7c809d8d7fc260ba61cb04510346a574b2781c59756e232b44046
true
56cf2d157f427b67a693c1a04a6b1ce0237e57854735516b338f3945b8f807a73a1c9222569dbb82d46ece311f6b3123394e6355
true
38165c3905cc6377d8bfbe50d07586964fb03b497962f5e5dcb10e92d20c28254364bb5fbf7d2b2eb1a15f33620a47cd9217b825
true
项目源码 :https://download.csdn.net/download/knight201603
有关加密算法的介绍请看这篇博客:
https://blog.csdn.net/wowotuo/article/details/77150796
最后
以上就是舒服机器猫最近收集整理的关于PBKDF2加密算法话不多说,上代码!!!的全部内容,更多相关PBKDF2加密算法话不多说,上代码内容请搜索靠谱客的其他文章。
发表评论 取消回复