PBKDF2 with bouncycastle in Java

后端 未结 3 1032
清酒与你
清酒与你 2020-12-04 10:56

I\'m trying to securely store a password in a database and for that I chose to store its hash generated using the PBKDF2 function. I want to do this using the bouncy castle

3条回答
  •  孤城傲影
    2020-12-04 11:30

    PBKDF2WithHmacSHA1 is already supported in BouncyCastle 1.60

    https://www.bouncycastle.org/specifications.html Password Hashing and PBE

    Test passed with OpenJDK Runtime Environment 18.9 (build 11.0.1+13):

        Security.addProvider(new BouncyCastleProvider());
    
        String password = "xrS7AJk+V6L8J?B%";
        SecureRandom rnd = new SecureRandom();
        int saltLength = 16;
        int keyLength = 128;
        int iterationCount = 10000;
    
        byte[] salt = new byte[saltLength];
        rnd.nextBytes(salt);
    
    //SunJCE
        SecretKeyFactory factorySun = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1", "SunJCE");
        KeySpec keyspecSun = new PBEKeySpec(password.toCharArray(), salt, iterationCount, keyLength);
        SecretKey keySun = factorySun.generateSecret(keyspecSun);
        System.out.println(keySun.getClass().getName());
        System.out.println(Hex.toHexString(keySun.getEncoded()));
    
    //BouncyCastle  
        SecretKeyFactory factoryBC = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1", "BC");
        KeySpec keyspecBC = new PBEKeySpec(password.toCharArray(), salt, iterationCount, keyLength);
        SecretKey keyBC = factoryBC.generateSecret(keyspecBC);
        System.out.println(keyBC.getClass().getName());
        System.out.println(Hex.toHexString(keyBC.getEncoded()));
    
        Assert.assertArrayEquals(keySun.getEncoded(), keyBC.getEncoded());
    

    The output is:

    com.sun.crypto.provider.PBKDF2KeyImpl
    e9b01389fa91a6172ed6e95e1e1a2611
    org.bouncycastle.jcajce.provider.symmetric.util.BCPBEKey
    e9b01389fa91a6172ed6e95e1e1a2611
    

提交回复
热议问题