PBKDF2 with Java


references

a general method

Following is a general method for generating PBKDF2 key in standard JDK.

byte[] pbkdf2(final char[] password, final byte[] salt,
              final int iterationCount, final int keyLength) {

    try {
        final SecretKeyFactory secretKeyFactory =
            SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        final KeySpec keySpec = new PBEKeySpec(
            password, salt, iterationCount, keyLength);
        try {
            final SecretKey secretKey =
                secretKeyFactory.generateSecret(keySpec);
            return secretKey.getEncoded();
        } catch (InvalidKeySpecException ikse) {
            throw new RuntimeException(ikse);
        }
    } catch (NoSuchAlgorithmException nsae) {
        throw new RuntimeException(nsae);
    }
}

And here comes a simplified version for 7.

byte[] pbkdf2(final char[] password, final byte[] salt,
              final int iterationCount, final int keyLength) {

    try {
        return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
            .generateSecret(new PBEKeySpec(password, salt, iterationCount,
                                           keyLength))
            .getEncoded();
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        throw new RuntimeException(e);
    }
}

password in byte[]

Maybe the password is already in a hashed or encoded form of byte[]. We can convert it to char[] like this.

char[] cassword(final byte[] bassword) {
    final char[] cassword = new char[bassword.length];
    for (int i = 0; i < cassword.length; i++) {
        cassword[i] = (char) (bassword[i] & 0xFF);
    }
    return cassword;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s