android - 使用私钥解密时出现 InvalidKeyException
问题描述
我正在尝试在 android 密钥库中生成公私密钥对后加密和解密数据。不知何故,它在解密过程中失败了。
我正在使用 RSA/ECB/OAEPWithSHA-256AndMGF1Padding 算法。
下面是我的代码
public void RSAEncryptDecryptTest() {
String plain = "SampleData";
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", ANDROID_KEY_STORE);
AlgorithmParameterSpec spec;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
// Below Android M, use the KeyPairGeneratorSpec.Builder.
spec = new KeyPairGeneratorSpec.Builder(mApplicationContext)
// You'll use the alias later to retrieve the key. It's a key for the key!
.setAlias(plain)
.build();
} else {
// On Android M or above, use the KeyGenparameterSpec.Builder and specify permitted
// properties and restrictions of the key.
spec = new KeyGenParameterSpec.Builder(plain, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT
| KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
/*.setKeySize(VisaSCPConstants.ALGORITHM_KEY_SIZE)*/
.setAlgorithmParameterSpec(new RSAKeyGenParameterSpec(VisaSCPConstants.ALGORITHM_KEY_SIZE, RSAKeyGenParameterSpec.F4))
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
.setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA512)
.setUserAuthenticationRequired(false)
.build();
}
kpg.initialize(spec);
KeyPair kp = kpg.genKeyPair();
PublicKey publicKey = kp.getPublic();
PrivateKey privateKey = kp.getPrivate();
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal(plain.getBytes());
System.out.println("Encrypted = " + Base64.encodeToString(encryptedBytes, Base64.NO_WRAP));
cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte [] decryptedBytes = cipher.doFinal(encryptedBytes);
if(plain.equals(new String(decryptedBytes))) {
System.out.println("TRUE");
} else {
System.out.println("FALSE");
}
} catch (Exception e) {
System.out.println("Exception " +e);
}
}
下面是我得到的例外。
InvalidKeyException - 没有提供者为 android.security.keystore.AndroidKeyStoreRSAPrivateKey 类的 RSA 密钥和导出格式提供 [RSA, ECB, OAEPWithSHA1AndMGF1Padding]
解决方案
推荐阅读
- r - 如何使用 geom_text() 或 geom_label() 精确定位 ggplot() 的文本标签。geom_text_repel() 不起作用。如果使用会引发错误
- python - Qt GUI 中的 Matplotlib 小部件拒绝对齐多个轴
- php - 如何安装 imagick 模块 PHP 7.2?
- apache-spark - PySpark SQL:用作表达式的子查询返回的不止一行:
- python - 使用 appJar 在树视图中查看 XML 文件
- python-3.x - ImportError:找不到库“GLU”
- angular - 从 Ionic 2 中的 Provider 调用页面函数
- c# - 迭代 JObject 键
- log4j - 日志语句在日志文件中重复
- javascript - 使用 jquery 选择选项