Reputation: 41
I am new to android development and I tried to generate the secret key for encryption and decryption and store that key inside the key store.But I got the below error while the app was being run.
java.security.NoSuchAlgorithmException: KeyGenerator AES implementation not found
at org.apache.harmony.security.fortress.Engine.notFound(Engine.java:190)
at org.apache.harmony.security.fortress.Engine.getInstance(Engine.java:183)
at javax.crypto.KeyGenerator.getInstance(KeyGenerator.java:164)
at javax.crypto.KeyGenerator.getInstance(KeyGenerator.java:135)
at com.example.lakshika.seureapp.codes.KeyStore.createSecretKey(KeyStore.java:56)
at com.example.lakshika.seureapp.codes.KeyStore.<init>(KeyStore.java:37)
This is the code which I have implemented.
public class KeyStore{
private static final String ANDROID_KEY_STORE = "AndroidKeyStore";
private static String DEFAULT_KEY = "";
private java.security.KeyStore keystore;
private String TAG = "Key store";
@TargetApi(Build.VERSION_CODES.M)
@RequiresApi(api = Build.VERSION_CODES.M)
public KeyStore(String alias) {
this.DEFAULT_KEY = alias;
Log.w(TAG,"start key store:"+ DEFAULT_KEY);
loadKeystore();
if (getSecretKey() == null) {
createSecretKey();
}
}
private void loadKeystore() {
try {
keystore = java.security.KeyStore.getInstance(ANDROID_KEY_STORE);
keystore.load(null);
} catch (IOException | NoSuchAlgorithmException |
CertificateException | KeyStoreException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
private void createSecretKey() {
try {
KeyGenerator keyGenerator = KeyGenerator
.getInstance(KeyProperties.KEY_ALGORITHM_AES,
ANDROID_KEY_STORE);
KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec
.Builder(DEFAULT_KEY, KeyProperties.PURPOSE_ENCRYPT |
KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
.setUserAuthenticationRequired(true);
keyGenerator.init(builder.build());
keyGenerator.generateKey();
} catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
SecretKey getSecretKey() {
try {
return (SecretKey) keystore.getKey(DEFAULT_KEY, null);
} catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
e.printStackTrace();
}
return null;
}
}
If anybody knows how to solve this error, please help me.Thank you.
Upvotes: 3
Views: 4536
Reputation: 39251
AES/CBC/PKCS7Padding is available since Android 23, but you are executing on Android 5 (android 21), so AES can not be used in your device
See https://developer.android.com/training/articles/keystore.html#SupportedCiphers
Upvotes: 2