使用以下代码生成RSA密钥:
RSAKeyGenParameterSpec rsaSpec = new RSAKeyGenParameterSpec(2048, RSAKeyGenParameterSpec.F4);
AlgorithmParameterSpec keyPairGeneratorSpec;
KeyGenParameterSpec.Builder specBuilder = new KeyGenParameterSpec.Builder(keyAlias, KeyProperties.PURPOSE_DECRYPT)
.setAlgorithmParameterSpec(rsaSpec)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP, KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
.setDigests(KeyProperties.DIGEST_SHA256);
keyPairGeneratorSpec = specBuilder.build();
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA, ANDROID_KEYSTORE);
keyPairGenerator.initialize(keyPairGeneratorSpec);
keyPairGenerator.generateKeyPair();
} catch(Exception e) {
//handle exception
}
然后将其用于使用以下命令在Java服务器上进行远程加密:
Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
cipher.doFinal(data);
然后在设备上,解密是这样完成的:
Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
rsaCipher.init(Cipher.DECRYPT_MODE, key);
return rsaCipher.doFinal(data);
一小部分时间,解密成功完成,但是在大多数情况下,我得到此异常:
javax.crypto.IllegalBlockSizeException
at android.security.keystore.AndroidKeyStoreCipherSpiBase.engineDoFinal(AndroidKeyStoreCipherSpiBase.java:519)
...
Caused by: android.security.KeyStoreException: Unknown error
at android.security.KeyStore.getKeyStoreException(KeyStore.java:695)
at android.security.keystore.KeyStoreCryptoOperationChunkedStreamer.doFinal(KeyStoreCryptoOperationChunkedStreamer.java:224)
at android.security.keystore.AndroidKeyStoreCipherSpiBase.engineDoFinal(AndroidKeyStoreCipherSpiBase.java:506)
at javax.crypto.Cipher.doFinal(Cipher.java:1736)
...
我在另外两个SO答案中发现了此异常,其中包括:https://stackoverflow.com/a/36020975/6552833,但它似乎并不相关,因为我一开始就没有使用OAEP加密。
答案 0 :(得分:1)
我有同样的问题。就我而言,我发现了2个原因:
android: allowsbackup ="true"
导致解密在某些设备上失败(发布版本。调试版本很好)。将此设置为False即可修复它。<application
android:name=".application.MyApplication"
tools:replace="android:allowBackup"
android:allowBackup="false">