首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java咸密码散列

Java咸密码散列
EN

Stack Overflow用户
提问于 2015-06-09 13:22:01
回答 3查看 404关注 0票数 0

我使用本教程来实现咸化密码散列,并将哈希和salt存储在数据库中。

代码:

代码语言:javascript
复制
/**
 * 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值保持不变?

EN

回答 3

Stack Overflow用户

发布于 2015-06-09 13:34:18

你应该使用:

代码语言:javascript
复制
System.out.println("HASH:" + Arrays.toString(hash)); // Store this in DB
System.out.println("SALT:" + Arrays.toString(salt)); // Store this in DB
票数 2
EN

Stack Overflow用户

发布于 2015-06-09 13:35:19

我尝试了您的最后一段代码,每次hashsalt都有新的值。

使用Arrays.toString转储值,您将看到这两个值都会改变:

代码语言:javascript
复制
    System.out.println("HASH:" + Arrays.toString( hash ) ); // Store this in DB
    System.out.println("SALT:" + Arrays.toString( salt ) ); // Store this in DB
票数 2
EN

Stack Overflow用户

发布于 2015-06-09 13:38:42

你需要把字节数组打印成字符串..。

使用Apache公域编解码器打印byte[]的内容

代码语言:javascript
复制
System.out.println( String.format("HASH : %s", Hex.encodeHexString( hash ) ));
System.out.println( String.format("SALT : %s", Hex.encodeHexString( salt ) ));
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30733272

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档