PBKDF2(Password-Based Key Derivation Function)。

通过哈希算法进行加密。由于哈希算法是单向的,能够将不论什么大小的数据转化为定长的“指纹”,并且无法被反向计算。

另外,即使数据源仅仅修改了一丁点。哈希的结果也会全然不同。

这种特性使得它很适合用于保存password。由于我们须要加密后的password无法被解密,同一时候也能保证正确校验每一个用户的password。可是哈希加密能够通过字典攻击和暴力攻击破解。

password加盐。盐是一个加入到用户的password哈希过程中的一段随机序列。

这个机制可以防止通过预先计算结果的彩虹表破解。每一个用户都有自己的盐,这种结果就是即使用户的password同样。通过加盐后哈希值也将不同。

为了校验password是否正确,我们须要储存盐值。通常和password哈希值一起存放在账户数据库中。或者直接存为哈希字符串的一部分。

public class PasswordEncryption {

	public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1";

	/**
* 盐的长度
*/
public static final int SALT_BYTE_SIZE = 32 / 2; /**
* 生成密文的长度
*/
public static final int HASH_BIT_SIZE = 128 * 4; /**
* 迭代次数
*/
public static final int PBKDF2_ITERATIONS = 1000; /**
* 对输入的password进行验证
*
* @param attemptedPassword
* 待验证的password
* @param encryptedPassword
* 密文
* @param salt
* 盐值
* @return 是否验证成功
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static boolean authenticate(String attemptedPassword, String encryptedPassword, String salt)
throws NoSuchAlgorithmException, InvalidKeySpecException {
// 用同样的盐值对用户输入的password进行加密
String encryptedAttemptedPassword = getEncryptedPassword(attemptedPassword, salt);
// 把加密后的密文和原密文进行比較,同样则验证成功。否则失败
return encryptedAttemptedPassword.equals(encryptedPassword);
} /**
* 生成密文
*
* @param password
* 明文password
* @param salt
* 盐值
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static String getEncryptedPassword(String password, String salt) throws NoSuchAlgorithmException,
InvalidKeySpecException { KeySpec spec = new PBEKeySpec(password.toCharArray(), fromHex(salt), PBKDF2_ITERATIONS, HASH_BIT_SIZE);
SecretKeyFactory f = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
return toHex(f.generateSecret(spec).getEncoded());
} /**
* 通过提供加密的强随机数生成器 生成盐
*
* @return
* @throws NoSuchAlgorithmException
*/
public static String generateSalt() throws NoSuchAlgorithmException {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[SALT_BYTE_SIZE];
random.nextBytes(salt); return toHex(salt);
} /**
* 十六进制字符串转二进制字符串
*
* @param   hex         the hex string
* @return              the hex string decoded into a byte array      
*/
private static byte[] fromHex(String hex) {
byte[] binary = new byte[hex.length() / 2];
for (int i = 0; i < binary.length; i++) {
binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
}
return binary;
} /**
* 二进制字符串转十六进制字符串
*
* @param   array       the byte array to convert
* @return              a length*2 character string encoding the byte array      
*/
private static String toHex(byte[] array) {
BigInteger bi = new BigInteger(1, array);
String hex = bi.toString(16);
int paddingLength = (array.length * 2) - hex.length();
if (paddingLength > 0)
return String.format("%0" + paddingLength + "d", 0) + hex;
else
return hex;
}
}

首先要生成一个盐值salt,再把原始password和salt加密得到密文。验证的时候,把用户输入的password和同样的盐值salt使用同样的加密算法得到一个密文,将这个密文和原密文相比較,同样则验证通过,反之则不通过。

	public static void main(String[] args) {
String password = "test";
String salt;
String ciphertext;
try { salt = PasswordEncryption.generateSalt();
ciphertext = PasswordEncryption.getEncryptedPassword(password, salt);
boolean result = PasswordEncryption.authenticate(password, ciphertext, salt); System.out.println(password + " " + password.length());
System.out.println(salt + " " + salt.length());
System.out.println(ciphertext + " " + ciphertext.length());
if (result) {
System.out.println("succeed");
} else {
System.out.println("failed");
}
} catch (NoSuchAlgorithmException e) {
System.out.println("NoSuchAlgorithmException");
} catch (InvalidKeySpecException e) {
System.out.println("InvalidKeySpecException");
}
}

測试结果为:

test  4
3aca9ca3fa80158b765ece7d0a45f2e8 32
592cb30e95efc720c5accf425ed5f2fe46aa332d9980e6daa234797de49cda731c2c18e667b4dd71ba33797a3dcddd312ff9b03d802bf1cc09aacb2a176cf741 128
succeed

參考资料:

1、https://en.wikipedia.org/wiki/PBKDF2

2、http://blog.jobbole.com/61872/#toc1

3、http://www.oschina.net/question/82993_59611?sort=time&p=1

PBKDF2加密的实现的更多相关文章

  1. PBKDF2加密

    password - the password that needs to be hashed. This should be convertedinto a char array before pa ...

  2. PHP & JAVA 实现 PBKDF2 加密算法

    PHP代码: /** * PBKDF2 加密函数 * 参考标准 * @link https://www.ietf.org/rfc/rfc2898.txt * * php官方函数将在php5.5发布 * ...

  3. Redis缓存数据库安全加固指导(二)

    背景 在众多开源缓存技术中,Redis无疑是目前功能最为强大,应用最多的缓存技术之一,参考2018年国外数据库技术权威网站DB-Engines关于key-value数据库流行度排名,Redis暂列第一 ...

  4. ASP.NET Core搭建多层网站架构【2-公共基础库】

    2020/01/28, ASP.NET Core 3.1, VS2019,Newtonsoft.Json 12.0.3, Microsoft.AspNetCore.Cryptography.KeyDe ...

  5. 密码学系列之:1Password的加密基础PBKDF2

    目录 简介 PBKDF2和PBKDF1 PBKDF2的工作流程 详解PBKDF2的key生成流程 HMAC密码碰撞 PBKDF2的缺点 总结 简介 1password是一个非常优秀的密码管理软件,有了 ...

  6. JS加密库Crypto-JS SEA加密

    http://www.seacha.com/tools/aes.html 在该网站测试 CryptoJS有很多加密方式网上查阅后有 CryptoJS (crypto.js) 为 JavaScript ...

  7. 【转】对抗拖库 ―― Web 前端慢加密

    0×00 前言 天下武功,唯快不破.但密码加密不同.算法越快,越容易破. 0×01 暴力破解 密码破解,就是把加密后的密码还原成明文密码.似乎有不少方法,但最终都得走一条路:暴力穷举.也许你会说还可以 ...

  8. [转载] TLS协议分析 与 现代加密通信协议设计

    https://blog.helong.info/blog/2015/09/06/tls-protocol-analysis-and-crypto-protocol-design/?from=time ...

  9. C#简单的加密类

    1.加密 public class EncryptHepler { // 验值 static string saltValue = "XXXX"; // 密码值 static st ...

随机推荐

  1. Linux Shell Scripting Cookbook 读书笔记 5

    sed,awk 1. sed (string editor) 使用-i可以将结果运用于原文件 sed 's/text1/text2/' file > newfile mv newfile fil ...

  2. element-ui 分页中的slot的用法(自定义分页显示内容)

    官方给的简单的例子以及效果. 最后弄成的效果: 按照文档在layout 添加slot, 这几个参数可以随意调换位置,然后分页显示效果会根据调换的位置显示相应内容.

  3. Tomcat修改默认根目录

    tomcat7默认的程序发布路径为tomcat/webapps/ROOT/下面 修改Tomcat配置文件server.xml <Host name="localhost" a ...

  4. 10.2&10.3 Xcode开发包

    10.2开发包下载链接 10.3开发包下载链接 Finder打开后,按command+shift+G前往这个地址: /Applications/Xcode.app/Contents/Developer ...

  5. Python数据结构2-----队列和堆

    一.线性结构:栈.队列.双端队列.列表 二.非线性结构:树.图.堆 [算法中看堆是非线性的,因为其相当于完全二叉树,但堆的存储元素是采用线性的顺序表数组来实现的] 三.队列: 1.队列类型:FIFO. ...

  6. 取得Linux系统的各种统计信息

    本文基于Linux 2.6.x内核 一.取得CPU信息(相关文件/proc/stat) 在一个系统中的/proct/stat文件内容如下 $ cat /proc/stat cpu 1039426 17 ...

  7. gradle多模块构建集成swagger

    1.首先说一下软件的版本:springboot:1.5.2:springcloud:D-SR1:swaager2:2.6.0:gradle:4.5.工程模块是分开的单独的entity,api,mapp ...

  8. 训练1-S

    给出N个正整数,检测每个数是否为质数.如果是,输出"Yes",否则输出"No". Input 第1行:一个数N,表示正整数的数量.(1 <= N < ...

  9. 训练1-U

    输入2个正整数A,B,求A与B的最小公倍数. Input 2个数A,B,中间用空格隔开.(1<= A,B <= 10^9) Output 输出A与B的最小公倍数. Sample Input ...

  10. 树状数组求LIS

    我真的是咸鱼啊 多少年前的基础了我竟然才弄明白,哭 用树状数组维护<=x的最上上升子序列的最大值即可啊Orz 我真的菜的一笔啊! #include <bits/stdc++.h> u ...