It is not recommended that you write the private key to your application. This key is compromised because the contents of your APK are not secret, and thus the key can be extracted from the APK. If you still believe that you need to do this despite this warning, read on.
To import the private key into Keystore Android, you need to present it as an instance of PrivateKey, and then you also need the X.509 certificate (for the public key corresponding to the private key), presented as an instance of X509Certificate. This is because the JCA KeyStore abstraction does not support storing private keys without a certificate.
To convert PKCS # 8 DER private key to PrivateKey:
PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate( new PKCS8EncodedKeySpec(privateKeyPkcs8));
To convert a PEM or DER certificate to a certificate:
Certificate cert = CertificateFactory.getInstance("X.509").generateCertificate( new ByteArrayInputStream(pemOrDerEncodedCert));
Finally, to import the private key and certificate into the Keystore entry in Android "myKeyAlias":
KeyStore ks = KeyStore.getInstance("AndroidKeyStore"); ks.load(null); ks.setKeyEntry("myKeyAlias", privateKey, null, new Certificate[] {cert});
See https://developer.android.com/reference/android/security/keystore/KeyProtection.html for more detailed examples.
source share