【发布时间】:2016-02-19 11:59:47
【问题描述】:
我正在为我正在开发的 Android 应用程序编写密码安全实用程序类。目前,它生成一个盐,然后使用该盐和密码作为参数生成一个散列。我需要一种方法,将存储在数据库中的哈希值与用户尝试登录时创建的哈希值进行比较。我应该使用Arrays.equals() 比较两个字节数组吗?
还是应该将byte[] dbHash、String password 和byte[] salt 作为参数并从那里开始?
这是目前为止的代码。
package fitfast.security;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.KeySpec;
import java.util.Arrays;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
public final class Authenticator {
private static final int length = 512;
private static final int iterations = 60000;
public static byte[] generateHash(String password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
String algorithm = "PBKDF2WithHmacSHA512";
KeySpec sp = new PBEKeySpec(password.toCharArray(), salt, iterations, length);
SecretKeyFactory kf = SecretKeyFactory.getInstance(algorithm);
return kf.generateSecret(sp).getEncoded();
}
public static byte[] generateSalt() throws NoSuchAlgorithmException {
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[8];
sr.nextBytes(salt);
return salt;
}
public static boolean check(byte[] hash, String password, byte[] salt) {
//code goes here
}
}
【问题讨论】:
标签: java cryptography passwords pbkdf2