PBKDF2 with SHA256 on android
Asked Answered
B

2

7

I want to generate a derived hash of a password using PBKDF2 with SHA256. with this SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1") this work but it use SHA1. With SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256") (or SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256","SC") when with spongycastle) i have an error.

How can i succeed to generate a hash using PBKDF2WithHmacSHA256?

Bread answered 24/7, 2012 at 9:48 Comment(0)
D
20

If you use version 1.47 or higher of SpongyCastle, you can invoke PBKDF2WithHmacSHA256 directly:

PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator(new SHA256Digest());
generator.init(PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(password), salt, iterations);
KeyParameter key = (KeyParameter)generator.generateDerivedMacParameters(keySizeInBits);

In versions of BC < 1.47, you could not specify SHA256 digest and it defaulted to SHA1.

Diego answered 8/3, 2013 at 21:6 Comment(2)
Yup, works. Android itself won't handle AES256 cryptography, so you need the above. The byte[] you get using "key.getKey()" and importing Spongy Castle is easy as adding the following into your dependencies in your build.gradle: compile 'com.madgag.spongycastle:core:1.54.0.0' compile 'com.madgag.spongycastle:prov:1.54.0.0' compile 'com.madgag.spongycastle:pkix:1.54.0.0' compile 'com.madgag.spongycastle:pg:1.54.0.0'Locksmith
compile 'com.madgag.spongycastle:core:1.54.0.0' is enough, you don't need the extra dependencies listed by @LocksmithBruner
P
2

Bouncy Castle doesn't support PBKDF2WithHmacSHA256 so this won't work. You can try implementing it yourself. Look at the source of PKCS5S2ParametersGenerator.java and replace SHA1Digest with SHA256Digest.

Placement answered 25/7, 2012 at 3:5 Comment(2)
Do you know if there is any existing library compatible with Android which have this implementation ?Bread
Haven't heard of any. Pretty much anything should be compatible though, since this doesn't really do anything platform-specific.Placement

© 2022 - 2024 — McMap. All rights reserved.