为JAVA可靠地实施PBKDF2-HMAC-SHA256

dgr*_*ory 21 java cryptography bouncycastle pbkdf2

对于JAVA,是否有可靠的PBKDF2-HMAC-SHA256实现?

我以前用bouncycastle加密,但它没有提供PBKDF2WithHmacSHA256'.

我不想自己编写加密模块.

你能推荐任何替代的库或算法(如果我能坚持使用bouncycastle)

(这里是bouncycastle支持算法的算法) http://www.bouncycastle.org/specifications.html

Pas*_*asi 36

直接使用BouncyCastle类:

PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest());
gen.init("password".getBytes("UTF-8"), "salt".getBytes(), 4096);
byte[] dk = ((KeyParameter) gen.generateDerivedParameters(256)).getKey();
Run Code Online (Sandbox Code Playgroud)


小智 24

它在Java 8中可用:

public static byte[] getEncryptedPassword(
                                         String password,
                                         byte[] salt,
                                         int iterations,
                                         int derivedKeyLength
                                         ) throws NoSuchAlgorithmException, InvalidKeySpecException {
    KeySpec spec = new PBEKeySpec(
                                 password.toCharArray(),
                                 salt,
                                 iterations,
                                 derivedKeyLength * 8
                                 );

    SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");

    return f.generateSecret(spec).getEncoded();
}
Run Code Online (Sandbox Code Playgroud)

  • @Kirby确保你只使用ASCII,Java 8有点奇怪,因为它只使用`char`的低8位(即Windows-1252兼容的字符编码). (3认同)