0

I'm trying to retrieve a private key, using the Bouncy Castle, Ktor and Kotlin.

fun readPrivateKey(filePath: String): Result<RSAPrivateKey> = runCatching {
  val pemParse = PEMParser(FileReader(filePath))
  val privateKey = PrivateKeyInfo.getInstance(pemParse.readObject())
  JcaPEMKeyConverter().getPrivateKey(privateKey) as RSAPrivateKey
}.onFailure { throw it }

but when testing the function, I get the following error

unknown object in getInstance: org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo java.lang.IllegalArgumentException: unknown object in getInstance: org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo

the error occurs in this line: privateKey = PrivateKeyInfo.getInstance(pemParse.readObject())

I generated my private key with the following code:

openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -aes-256-cbc -out development_erp_private.key

what am I doing wrong?

  • With your OpenSSL statement you have created an *encrypted* RSA private key in PKCS#8 format. `PEMParser` returns a `PKCS8EncryptedPrivateKeyInfo`. [Here](https://stackoverflow.com/a/69070577/9014097) you can find a Java code which should be easy to port to Kotlin (only the `o instanceof PKCS8EncryptedPrivateKeyInfo` branch). For it to work, you need to import a current BC version (and remove any old BC provider *beforehand*). – Topaco Dec 06 '22 at 20:43
  • Thanks @Topaco works fine. I had used a similar code to get the public key and it worked. I didn't understand why it didn't work with the private key. – Rodrigo Batista Dec 07 '22 at 10:07

0 Answers0