Store RSA public key into Android Keystore

153 Views Asked by At

I'm trying to insert a public key into Android Keystore (also generated by Android Keystore) as an X509 certificate as:

 // Convert String into a public key
 val keyText = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxfA62QI++RO45nV241wEUT19DtaiF/49PKfCiUeoVu6tSb4us0Whl1i1u76cznWeTgBuqOXPt67feoegaIs6kMT1FMFNK9bHU02ufQ9DhmC/cLknXZtYHfxaerAUVdL1b8maKuXmkxiIBjAOU57PdSLapG29a41+Z9wWmHW5NMq11PZFlW9qFJ+Splq1EV9NDFsMbN9WAqGhRO1tnyj3DaqsYnS/HKyuym9J2KVWJSVUMrXcNDm9uUnchdCJ4QkPQQbDJ/QQVFCM1q7XSgNAgR/7UAlN8tdb0QobIhG0S6QGGhgodYDS397fDPAEtX2CK8VVpQOmbrjrZWKGLQ2bqQIDAQAB"
 val decodedKeyBytes = Base64.decode(keyText, Base64.DEFAULT)
 val keySpec = X509EncodedKeySpec(decodedKeyBytes)
 val keyFactory = KeyFactory.getInstance("RSA")
 val newPubKey = keyFactory.generatePublic(keySpec)

 val certificateFactory = CertificateFactory.getInstance("X.509")
 val x509Certificate = certificateFactory.generateCertificate(
     newPubKey.encoded.inputStream()
   ) as X509Certificate

 // Insert into AndroidKeyStore
 val ks: KeyStore = KeyStore.getInstance("AndroidKeyStore").apply {load(null)}
 ks.setCertificateEntry("KEY_UID", x509Certificate)

I get the following exception while trying to generate the X509 certificate from the public key:

java.security.cert.CertificateException: 
  com.android.org.conscrypt.OpenSSLX509CertificateFactory$ParsingException:
  java.lang.RuntimeException: error:0c00006d:ASN.1 encoding routines:OPENSSL_internal:DECODE_ERROR 
    at com.android.org.conscrypt.OpenSSLX509CertificateFactory.engineGenerateCertificate(OpenSSLX509CertificateFactory.java:303)

I'm sure newPubKey is correct, since it matches the object originally produced by the Android Keystore. Am I missing some configuration for the X509 certificate? Is it even possible to store a public key as a certificate? Is there any other way of doing it?

Thank you

0

There are 0 best solutions below