Convert private key in PEM format

后端 未结 3 1316
后悔当初
后悔当初 2021-01-04 22:52

I have created a self-signed certificate with Java code and added into KeyStore. Now I want to export Private key and Certificate created, into a file in PEM format. Is it

相关标签:
3条回答
  • 2021-01-04 23:29

    You use Certificate.getEncoded() and Key.getEncoded() to get DER and do the base 64 encoding and header/footer manually, e.g. using DatatypeConverter.printBase64Binary() or some other way. Something like:

    certpem = "-----BEGIN CERTIFICATE-----\n" +
              DatatypeConverter.printBase64Binary(chain[0].getEncoded())) +
              "\n-----END CERTIFICATE-----\n";
    keypem  = "-----BEGIN RSA PRIVATE KEY-----\n" +
              DatatypeConverter.printBase64Binary(privKey.getEncoded())) +
              "\n-----END RSA PRIVATE KEY-----\n";
    
    0 讨论(0)
  • 2021-01-04 23:48

    Thanks Daniel Roethlisberger, for your reply. I got great help from your reply..

    Implements in Java as below

    String encodedString = "-----BEGIN PRIVATE KEY-----\n";
                encodedString = encodedString+Base64.getEncoder().encodeToString(Enrollment2.getKey().getEncoded())+"\n";
                encodedString = encodedString+"-----END PRIVATE KEY-----\n";
    
    0 讨论(0)
  • 2021-01-04 23:52

    On Android, you can use the following Kotlin extension function:

    import android.util.Base64
    import java.security.PublicKey
    
    fun PublicKey.toPemString(): String {
        val publicKeyBase64: String = Base64.encodeToString(this.encoded, Base64.NO_WRAP)
        return publicKeyBase64.chunked(64).joinToString(
            separator = "\n",
            prefix = "-----BEGIN PUBLIC KEY-----\n",
            postfix = "\n-----END PUBLIC KEY-----\n"
        )
    }
    
    0 讨论(0)
提交回复
热议问题