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

时间:2014-03-22 17:13:25

标签: java cryptography bouncycastle pbkdf2

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

我曾经使用bouncycastle进行加密,但它没有提供PBKDF2WithHmacSHA256'。

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

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

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

3 个答案:

答案 0 :(得分:34)

直接使用BouncyCastle类:

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

答案 1 :(得分:23)

它在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();
}

答案 2 :(得分:1)

使用海绵宝宝(Android上的Java)

如果直接在Java上使用bouncycastle,请用bouncycastle替换spongycastle

import org.spongycastle.crypto.generators.PKCS5S2ParametersGenerator;
import org.spongycastle.crypto.digests.SHA256Digest;
import org.spongycastle.crypto.params.KeyParameter;

public class Crypto {
    public String pbkdf2(String secret, String salt, int iterations, int keyLength) {
        PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest());
        byte[] secretData = secret.getBytes();
        byte[] saltData = salt.getBytes();
        gen.init(secretData, saltData, iterations);
        byte[] derivedKey = ((KeyParameter)gen.generateDerivedParameters(keyLength * 8)).getKey();    
        return toHex(derivedKey);
    }

    private static String toHex(byte[] bytes) {
        BigInteger bi = new BigInteger(1, bytes);
        return String.format("%0" + (bytes.length << 1) + "x", bi);
    }
}