Reputation: 271
I am using one library which encrypts the data using bouncy castle library in android project which used AES_CFB encryption mode. Earlier this library was using CBC and in my android application I was able to decrypt the key by using below code.
private fun getPrivateKey(certObject: PKCS8EncryptedPrivateKeyInfo, keyPassPhrase: String): PrivateKey? {
val bouncyCastleProvider = BouncyCastleProvider()
val decryptionProvider: InputDecryptorProvider =
JceOpenSSLPKCS8DecryptorProviderBuilder().setProvider(bouncyCastleProvider)
.build(keyPassPhrase.toCharArray())
val info = certObject.decryptPrivateKeyInfo(decryptionProvider)
val converter = JcaPEMKeyConverter()
return converter.getPrivateKey(info)
}
Now that library has changed the encryption mode to AES_CFB. So the above code is giving the below exception while decrypting it on this line
val info = certObject.decryptPrivateKeyInfo(decryptionProvider)
Exception:
Method threw 'org.bouncycastle.pkcs.PKCSException' exception.
unable to read encrypted data: no key size for algorithm:2.16.840.1.101.3.4.1.44
Can someone help in how to switch from CBC to CFB using bouncy castle?
Adding Sample code here
public class Application {
private final static String passphrase = "password";
public static void main(String[] args) {
try {
BouncyCastleProvider securityProvider = new BouncyCastleProvider();
Security.addProvider(securityProvider);
PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = getPrivateKeyInfo();
System.out.println("Private key algorithm encrypted: " + encryptedPrivateKeyInfo.getEncryptionAlgorithm().getAlgorithm());
InputDecryptorProvider decryptionProvider = new JceOpenSSLPKCS8DecryptorProviderBuilder()
.setProvider(securityProvider)
.build(passphrase.toCharArray());
PrivateKeyInfo privateKeyInfo = encryptedPrivateKeyInfo.decryptPrivateKeyInfo(decryptionProvider);
System.out.println("Private key algorithm decrypted: " + privateKeyInfo.getPrivateKeyAlgorithm().getAlgorithm());
}catch (Exception e){
System.out.println(e);
} }
private static PKCS8EncryptedPrivateKeyInfo getPrivateKeyInfo() throws IOException {
InputStream privateKeyInputStream = new FileInputStream("src/main/resources/key.k8");
PEMParser pemParser = new PEMParser(new InputStreamReader(privateKeyInputStream, StandardCharsets.UTF_8));
Object pemObject = pemParser.readObject();
return (PKCS8EncryptedPrivateKeyInfo) pemObject;
}
}
And the src/main/resources/key.k8 file contains
-----BEGIN ENCRYPTED PRIVATE KEY-----
<private key encrypted with AES_CFB_256 encryption using bouncy castle>
-----END ENCRYPTED PRIVATE KEY-----
Upvotes: 1
Views: 136