Java salted密码哈希

时间:2015-06-09 13:22:01

标签: java

我正在使用 this tutorial 来实施salted密码哈希,并将哈希和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值保持不变?

3 个答案:

答案 0 :(得分:2)

您应该使用:

System.out.println("HASH:" + Arrays.toString(hash)); // Store this in DB
System.out.println("SALT:" + Arrays.toString(salt)); // Store this in DB

答案 1 :(得分:2)

我尝试了您的上一个代码,我发现每次hashsalt都有新值。

使用Arrays.toString转储值,您会看到两个值都发生了变化:

    System.out.println("HASH:" + Arrays.toString( hash ) ); // Store this in DB
    System.out.println("SALT:" + Arrays.toString( salt ) ); // Store this in DB

答案 2 :(得分:2)

您需要将字节数组打印为字符串...

使用Apache Commons Codec打印 byte []

的内容
System.out.println( String.format("HASH : %s", Hex.encodeHexString( hash ) ));
System.out.println( String.format("SALT : %s", Hex.encodeHexString( salt ) ));