gpt4 book ai didi

java - Android 中未找到 KeyGenerator AES 实现

转载 作者:太空宇宙 更新时间:2023-11-04 10:35:01 26 4
gpt4 key购买 nike

我是 Android 开发新手,我尝试生成用于加密和解密的 key 并将该 key 存储在 key 存储中。但是在运行应用程序时出现以下错误。

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;
}

}

如果有人知道如何解决这个错误,请帮助我。谢谢。

最佳答案

AES/CBC/PKCS7Padding 自 Android 23 起可用,但您在 Android 5 (android 21) 上执行,因此无法在您的设备中使用 AES

参见https://developer.android.com/training/articles/keystore.html#SupportedCiphers

关于java - Android 中未找到 KeyGenerator AES 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49588938/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com