Android KeyStore - How to save an RSA PrivateKey

前端 未结 1 1120
名媛妹妹
名媛妹妹 2020-12-14 10:40

I receive from a web service(made by myself) an RSA PrivateKey PKCS#8 encoded in a base 64 String. My Android app must save this key somewhere into the phone securely.

相关标签:
1条回答
  • 2020-12-14 10:43

    In KeyStore the private keys must be stored along with a certificate (even a fake self-signed certificate). To store your key in the AndroidKeyStore you should follow these steps:

    1. decode the Base64 PKCS#8 to get a PrivateKey instance
    2. either the web service sends a certificate (or certificate chain) along with the private key or the PKCS#8 blob also contain the public key.
    3. if required you need to generate a certificate for the private key. The BouncyCastle library can do this (a code sample can be found here).

    Now you can add your key to the keystore.

    PrivateKey myKey = getKey();
    X509Certificate certificate = getCertificate();
    KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
    keyStore.load(null);
    keystore.setKeyEntry("anAlias", myKey, null, new Certificate[] { certificate });
    
    0 讨论(0)
提交回复
热议问题