Search code examples
javaandroidrsabouncycastlespongycastle

Android PrivateKey to BouncyCastle PrivateKeyInfo?


I am trying to use Bouncy/SpongyCastle's OAEP encoding to decode some wrapped data. However, the SpongyCastle API for initialising the OAEPEncoding class requires CipherParameters. In my case, I'm trying to unwrap something using an Android PrivateKey, so I assume I would need to somehow convert the key to AsymmetricKeyParam and stick that in the OAEPEncoding.init function. However, I really tried searching for something similar but most of the examples show initialising that by doing getPrivate().getEncoded(). However, Android doesn't allow you to get the raw private key so I'm not sure how to approach this...
EDIT: The reason why I'm using BC's OAEP classes is to use OAEP with SHA-256


Solution

  • The key material stored in the Android Keystore is not accessible. You can use the keys but you can not extract them. It is a security restriction. privateKey.getEncoded() will allways be null, and you will not be able to extract the parameters to create a key with SpongyCastle.

    See Security Features of Android Keystore

    Extraction Prevention

    Key material of Android Keystore keys is protected from extraction using two security measures:

    • Key material never enters the application process. When an application performs cryptographic operations using an Android Keystore key, behind the scenes plaintext, ciphertext, and messages to be signed or verified are fed to a system process which carries out the cryptographic operations. If the app's process is compromised, the attacker may be able to use the app's keys but will not be able to extract their key material (for example, to be used outside of the Android device).

    If you want to use OAEP you need to create and store the keys yourself or targe Android>=23