Android KeyGenerator 生成 Key 报错:'java.security.NoSuchAlgorithmException: KeyGenerator AES implementation not found'
Android KeyGenerator 生成 Key 报错:'java.security.NoSuchAlgorithmException: KeyGenerator AES implementation not found'
问题描述:
在 Android 中使用 KeyGenerator 生成 Key 时,报错如下:
java.security.NoSuchAlgorithmException: KeyGenerator AES implementation not found
at java.security.KeyGenerator.<init>(KeyGenerator.java:168)
at java.security.KeyGenerator.getInstance(KeyGenerator.java:223)
解决方案:
这个问题一般是由于 Android 系统中没有安装 AES 加密算法所导致的,可以通过在应用中自己添加 AES 算法的方式解决。
具体操作步骤如下:
- 在项目的 build.gradle 文件中添加如下依赖:
implementation 'org.bouncycastle:bcprov-jdk15on:1.60'
- 在生成 Key 之前,先调用如下代码:
Security.addProvider(new BouncyCastleProvider());
这个代码会在系统中添加 BouncyCastle 算法提供者,从而支持 AES 算法。
完整的示例代码如下:
Security.addProvider(new BouncyCastleProvider());
KeyGenerator keyGenerator = KeyGenerator.getInstance('AES', 'BC');
keyGenerator.init(128);
SecretKey secretKey = keyGenerator.generateKey();
byte[] keyBytes = secretKey.getEncoded();
注意事项:
- 需要在 AndroidManifest.xml 文件中添加以下权限:
<uses-permission android:name='android.permission.INTERNET' />
- 需要在应用启动时初始化 BouncyCastleProvider,可以在 Application 的 onCreate 方法中添加如下代码:
Security.addProvider(new BouncyCastleProvider());
原文地址: https://www.cveoy.top/t/topic/lC12 著作权归作者所有。请勿转载和采集!