我使用本教程来实现咸化密码散列,并将哈希和salt存储在数据库中。
代码:
/**
* Creates the salted hash.
*
* @param password
* the password
* @return the map
*/
@SuppressWarnings("unused")
private static Map<byte[], byte[]> createSaltedHash(String password) {
Map<byte[], byte[]> saltedHash = new HashMap<byte[], byte[]>();
byte[] hash = null;
byte[] salt = null;
final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1";
// The following may be changed without breaking existing hashes.
final int SALT_BYTE_SIZE = 24;
final int HASH_BYTE_SIZE = 24;
final int PBKDF2_ITERATIONS = 1000;
final int ITERATION_INDEX = 0;
final int SALT_INDEX = 1;
final int PBKDF2_INDEX = 2;
SecureRandom secureRandom = new SecureRandom();
salt = new byte[SALT_BYTE_SIZE];
secureRandom.nextBytes(salt);
//byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt,
PBKDF2_ITERATIONS, (HASH_BYTE_SIZE * 8));
try {
SecretKeyFactory skf = SecretKeyFactory
.getInstance(PBKDF2_ALGORITHM);
hash = skf.generateSecret(spec).getEncoded();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
System.out.println("HASH:" + hash); // Store this in DB
System.out.println("SALT:" + salt); // Store this in DB
saltedHash.put(hash, salt);
return saltedHash;
}问题:
为什么在更改密码字符串时,salt和hash值保持不变?
发布于 2015-06-09 13:34:18
你应该使用:
System.out.println("HASH:" + Arrays.toString(hash)); // Store this in DB
System.out.println("SALT:" + Arrays.toString(salt)); // Store this in DB发布于 2015-06-09 13:35:19
我尝试了您的最后一段代码,每次hash和salt都有新的值。
使用Arrays.toString转储值,您将看到这两个值都会改变:
System.out.println("HASH:" + Arrays.toString( hash ) ); // Store this in DB
System.out.println("SALT:" + Arrays.toString( salt ) ); // Store this in DB发布于 2015-06-09 13:38:42
你需要把字节数组打印成字符串..。
使用Apache公域编解码器打印byte[]的内容
System.out.println( String.format("HASH : %s", Hex.encodeHexString( hash ) ));
System.out.println( String.format("SALT : %s", Hex.encodeHexString( salt ) ));https://stackoverflow.com/questions/30733272
复制相似问题