Last active
August 29, 2015 14:05
-
-
Save nremond/f6b0c87b99e09c07e8ee to your computer and use it in GitHub Desktop.
Load a PEM file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.InetSocketAddress | |
import java.security.interfaces.RSAPrivateKey | |
import java.security.cert.X509Certificate | |
def loadPemFile(pemPath: String): (X509Certificate, RSAPrivateKey) = { | |
import java.io.ByteArrayInputStream | |
import java.security.KeyFactory | |
import java.security.cert.CertificateFactory | |
import java.security.spec.PKCS8EncodedKeySpec | |
import javax.xml.bind.DatatypeConverter | |
def parseDERFromPEM(pem: Array[Byte], beginDelimiter: String, endDelimiter: String): Array[Byte] = { | |
val data = new String(pem) | |
val token = data.split(beginDelimiter)(1).split(endDelimiter)(0) | |
DatatypeConverter.parseBase64Binary(token) | |
} | |
def generatePrivateKeyFromDER(keyBytes: Array[Byte]): RSAPrivateKey = { | |
val spec = new PKCS8EncodedKeySpec(keyBytes) | |
val factory = KeyFactory.getInstance("RSA") | |
factory.generatePrivate(spec).asInstanceOf[RSAPrivateKey] | |
} | |
def generateCertificateFromDER(certBytes: Array[Byte]): X509Certificate = { | |
val factory = CertificateFactory.getInstance("X.509") | |
factory.generateCertificate(new ByteArrayInputStream(certBytes)).asInstanceOf[X509Certificate] | |
} | |
import java.nio.file.{ Files, Paths } | |
val certAndKeyBytes = Files.readAllBytes(Paths.get(pemPath)) | |
val certBytes = parseDERFromPEM(certAndKeyBytes, "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----") | |
val keyBytes = parseDERFromPEM(certAndKeyBytes, "-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----") | |
val cert = generateCertificateFromDER(certBytes) | |
val key = generatePrivateKeyFromDER(keyBytes) | |
(cert, key) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment