I am trying to figure out how to export private key from the X509Certificate
instance as a PEM string encoded.
What I have done to far is to export certificate as PEM encoded:
import org.bouncycastle.jce.provider.BouncyCastleProvider
import org.bouncycastle.openssl.jcajce.JcaPEMWriter
import java.io.StringWriter
import java.security.KeyPairGenerator
import java.security.Security
import java.security.spec.ECGenParameterSpec
fun main(args: Array<String>) {
Security.addProvider(BouncyCastleProvider())
val kpGen = KeyPairGenerator.getInstance("EC", "BC")
kpGen.initialize(ECGenParameterSpec("P-256"))
val keyPair = kpGen.generateKeyPair()
val cert = SelfSignedCertGenerator().generate(keyPair, "SHA512WithECDSA", "localhost", 730)
val sw = StringWriter()
JcaPEMWriter(sw).use { jpw ->
jpw.writeObject(cert)
}
println(sw.toString())
}
the output shows the expected result:
-----BEGIN CERTIFICATE-----
MIIBcDCCARWgAwIBAgIGAYHjRWOUMAoGCCqGSM49BAMEMBQxEjAQBgNVBAMMCWxv
Y2FsaG9zdDAeFw0yMjA3MDkxNDAzMDRaFw0yNDA3MDgxNDAzMDRaMBQxEjAQBgNV
BAMMCWxvY2FsaG9zdDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABF G CHHQ56C
AgWN2G9PUemJTNGVdefWWuPVA5Oruepm9yOM69H5tPia0V/BCDlVHQrJ8Q0yC4Fa
uuM3HP42VJ6jUzBRMB0GA1UdDgQWBBTYf15PsEN2DaNaG3YFDL84SgXZvTAfBgNV
HSMEGDAWgBTYf15PsEN2DaNaG3YFDL84SgXZvTAPBgNVHRMBAf8EBTADAQH/MAoG
CCqGSM49BAMEA0kAMEYCIQCr9MrSGW3eimfDodqC6a4nxbusOUQcFz2 DHYFrZTx
AAIhAPRJ70basMDBOBdOQnN2DgxbGSHzsixZ7qajakRTlKKz
-----END CERTIFICATE-----
The question is how to export the generated private key as PEM encoded?
CodePudding user response:
Just pass your private key to the JcaPEMWriter::writeObject
:
JcaPEMWriter(sw).use {
w -> w.writeObject(keyPair.private)
}
println(sw.toString())
which gives :
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIK2XWix f1aRSh7sH4NSYQeCBsCfOBjFATKiJLnD4UPdoAoGCCqGSM49
AwEHoUQDQgAEIQAArKsROcQ8l2aZUO a3zm 03 a9ToTrpE Ysi9Pm5 oQoy1Oro
kLiJxihn2rgQFspUuQ0cRdwj8HKo2MsIzQ==
-----END EC PRIVATE KEY-----