I am making an android app which uses PBKDF2 With Hmac Sha256. I implemented the function but when I test it on android 5.0 device it gives NoSuchAlgorithmException. How can I implement manually PBKDF2 for android 5.0?
I am using this for PBKDF2 and AES 256 encryption:
@RequiresApi(api = Build.VERSION_CODES.O)
public static String encrypt(String strToEncrypt, String SECRET_KEY, String SALT) {
try {
byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
IvParameterSpec ivspec = new IvParameterSpec(iv);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), SALT.getBytes(), 100000, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));
} catch (Exception e) {
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
Thanks!
For Android SDK < 26 You could use a PBKDF class written by Will Glozer that is available here: https://github.com/wg/scrypt/blob/master/src/main/java/com/lambdaworks/crypto/PBKDF.java.
To derive a secret key for AES-256 you call the class like this:
Here is the complete class code in case it goes away in the future: