PBKDF2加密

PBKDF2算法通过多次hash来对密码进行加密。原理是通过password和salt进行hash,然后将结果作为salt在与password进行hash,多次重复此过程,生成最终的密文。

如何验证密码正确?

用相同的盐值对用户输入的密码进行加密,如果与密文比对,相同则密码正确。

// 迭代次数
public static final int PBKDF2_ITERATIONS = 1000;

public class PBKDF2
{
public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1";

//盐的长度
public static final int SALT_SIZE = 16;

//生成密文的长度
public static final int HASH_SIZE = 32;

// 迭代次数
public static final int PBKDF2_ITERATIONS = 1000;

/**
* 对输入的密码进行验证
*
*/
public static boolean verify(String password, String salt, String key)
throws NoSuchAlgorithmException, InvalidKeySpecException {
// 用相同的盐值对用户输入的密码进行加密
String result = getPBKDF2(password, salt);
// 把加密后的密文和原密文进行比较,相同则验证成功,否则失败
return result.equals(key);
}

/**
* 根据password和salt生成密文
*
*/
public static String getPBKDF2(String password, String salt) throws NoSuchAlgorithmException,
InvalidKeySpecException {
//将16进制字符串形式的salt转换成byte数组
byte[] bytes = DatatypeConverter.parseHexBinary(salt);
KeySpec spec = new PBEKeySpec(password.toCharArray(), bytes, PBKDF2_ITERATIONS, HASH_SIZE * 4);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
byte[] hash = secretKeyFactory.generateSecret(spec).getEncoded();
//将byte数组转换为16进制的字符串
return DatatypeConverter.printHexBinary(hash);
}


/**
* 生成随机盐值
*
*/
public static String getSalt() throws NoSuchAlgorithmException {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] bytes = new byte[SALT_SIZE / 2];
random.nextBytes(bytes);
//将byte数组转换为16进制的字符串
String salt = DatatypeConverter.printHexBinary(bytes);
return salt;
}

public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
String salt = getSalt();
System.out.println(salt);
String pdkdf2Password = getPBKDF2("haiying", salt);
System.out.println(pdkdf2Password);
//System.out.println(verify("admin","278663392F2E837C","02C3E6550F0AB1EAEB54E8351D633FB8"));
}
 
posted @ 2021-03-26 10:48  下饭  阅读(824)  评论(0编辑  收藏  举报