我通常会在这里找到大部分问题的答案,但这次我需要问:-).
我们在Android 8.0(API级别26)上运行的某个应用程序中遇到了RSA加密/解密问题.
我们一直在使用带有"RSA/ECB/OAEPWithSHA-256AndMGF1Padding"的RSA,它适用于Android 7.1以上的所有版本.在调用Cipher.doFinal()时,在Android 8.0上运行的相同代码会抛出IllegalBlocksizeException.
以下是重现问题的代码:
private KeyStore mKeyStore;
private static final String KEY_ALIAS = "MyKey";
void testEncryption() throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyStoreException, IOException, CertificateException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException, UnrecoverableEntryException, NoSuchPaddingException {
mKeyStore = KeyStore.getInstance("AndroidKeyStore");
mKeyStore.load(null);
// Generate Key Pair -------------------------------------
KeyPairGenerator kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
kpg.initialize(new KeyGenParameterSpec.Builder(
KEY_ALIAS,
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
.setKeySize(2048)
.build());
KeyPair kp = kpg.generateKeyPair();
// Encrypt -----------------------------------------------
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)mKeyStore.getEntry(KEY_ALIAS, null);
PublicKey publicKey = (PublicKey) privateKeyEntry.getCertificate().getPublicKey();
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey); …Run Code Online (Sandbox Code Playgroud)