Parsing certs/keys from Strings in Scala
I found it surprisingly difficult to get a straight answer online about how to parse the text of an RSA key-pair or certificate into their corresponding Java objects. Here's a basic step-by-step of how to do that. (All of this should basically apply to Java as well). A full example is at the bottom.
Create a factory what you're trying to decode.
// For X.509 certificates
val x509CertFactory: CertificateFactory = CertificateFactory.getInstance("X.509")
// For RSA keys
val rsaKeyFactory: KeyFactory = KeyFactory.getInstance("RSA")Strip unnecessary characters. Remove new lines and header/footer tags.
def stripCertText(certText: String): String =
certText
.stripMargin
.replace("\n", "")
.replace("-----BEGIN CERTIFICATE-----", "")
.replace("-----END CERTIFICATE-----", "")
def stripPrivateKeyText(keyText: String): String =
keyText
.stripMargin
.replace("\n", "")
.replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "")
def stripPublicKeyText(keyText: String): String =
keyText
.stripMargin
.replace("\n", "")
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")Decode base-64
Generate certificate/key
Full example for parsing a certificate:
Last updated
Was this helpful?