I generate the RSA key pair and the aes key, then wrap the aes key using the rsa public key.Then try to import the encrypted AES key to Android Keystore but a meaningless error message appears
That line generating the error :
keyStore.setEntry(IMPORTED_KEY_ALIAS, wrappedKeyEntry, null);?
Error message:
:java.security.KeyStoreException: Failed to import wrapped key. Keystore error code: -1000
at android.security.keystore2.AndroidKeyStoreSpi.setWrappedKeyEntry(AndroidKeyStoreSpi.java:983)
I can see that the wrapped key is created correctly by debugging.
private KeyPair getOrCreateKeyPair() throws Exception {
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
if (!keyStore.containsAlias(KEY_ALIAS)) {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
keyPairGenerator.initialize(
new KeyGenParameterSpec.Builder(KEY_ALIAS,
KeyProperties.PURPOSE_WRAP_KEY | KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setKeySize(2048)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
.build());
return keyPairGenerator.generateKeyPair();
} else {
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(KEY_ALIAS, null);
return new KeyPair(privateKeyEntry.getCertificate().getPublicKey(), privateKeyEntry.getPrivateKey());
}
}
private SecretKey generateAESKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(256);
return keyGenerator.generateKey();
}
private byte[] wrapKey(PublicKey publicKey, SecretKey aesKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPPadding", "BC");
cipher.init(Cipher.WRAP_MODE, publicKey);
return cipher.wrap(aesKey);
}
private void importWrappedKey(byte[] wrappedKey) throws Exception {
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null, null);
AlgorithmParameterSpec spec = new KeyGenParameterSpec.Builder(IMPORTED_KEY_ALIAS,
KeyProperties.PURPOSE_WRAP_KEY )
.setDigests(KeyProperties.DIGEST_SHA256)
.build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
WrappedKeyEntry wrappedKeyEntry = new WrappedKeyEntry(wrappedKey, KEY_ALIAS, "RSA/ECB/OAEPPadding", spec);
keyStore.setEntry(IMPORTED_KEY_ALIAS, wrappedKeyEntry, null);
}
}