我是Android开发的新手,我尝试生成加密和解密的密钥,并将该密钥存储在密钥库中。但是在应用程序运行时我收到了以下错误。
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)
这是我实施的代码。
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;
}
}
如果有人知道如何解决这个错误,请帮助我。谢谢。
答案 0 :(得分:0)
AES / CBC / PKCS7Padding自Android 23起可用,但您在Android 5(Android 21)上执行,因此AES无法在您的设备中使用
请参阅https://developer.android.com/training/articles/keystore.html#SupportedCiphers