Error when importing private key into Java

702 views Asked by At

UPDATE: This suggestion solved my problem

I created a private key using OpenSSL and obtained a corresponding public certificate. I created the private key using the following command:

openssl req -out CSR.csr -new -newkey rsa:2048 -nodes -keyout privateKey.key

Both the private key and public certificate are Base64 encoded.

The format of the PEM encoded private key is something like this:

-----BEGIN ENCRYPTED PRIVATE KEY-----
...
-----END ENCRYPTED PRIVATE KEY-----

The public certificate is in the format:

-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----

Now, I am importing them to my Java application to create a SSLContext. There are two things that I want to avoid:

  • Using Java keystore (or .jks)
  • Using BouncyCastle

I have the following Java code so far:

Step 1: Reading the private key and public certificate:

byte[] certBytes = convertFileToBytes(new File("public.cer"));
byte[] keyBytes = convertFileToBytes(new File("private.key"));

Step 2: Generate public certificate from the binary encoded bytes:

private static X509Certificate generatePublicCert(byte[] certBytes) {
    CertificateFactory factory = CertificateFactory.getInstance("X.509");
    return (X509Certificate)factory.generateCertificate(new ByteArrayInputStream(certBytes));
}

Step 3: Generate private key from the binary encoded bytes:

private static PrivateKey generatePrivateKey(byte[] keyBytes) {
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory factory = KeyFactory.getInstance("RSA");
    return factory.generatePrivate(spec);
}

Step 4: Generate a SSLContext:

private static SSLContext getContext() {
    X509Certificate cert = generatePublicCert(certBytes);
    PrivateKey key = generatePrivateKey(keyBytes);

    KeyStore keyStore = KeyStore.getInstance("JKS"); // Do I still need this?
    keyStore.load(null);
    keyStore.setCertificateEntry("cert-alias", cert);
    keyStore.setKeyEntry("key-alias", key, "MyPassphrase".toCharArray(), new Certificate[] {cert});

    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(keyStore, "MyPassphrase".toCharArray());

    KeyManager[] km = kmf.getKeyManagers();
    context.init(km, null, null);
    return context;
 }

But, I am getting an error at Step 3:

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
    at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(Unknown Source)
    at java.security.KeyFactory.generatePrivate(Unknown Source)

What am I doing wrong?

1

There are 1 answers

0
duffy356 On

Are you sure, that your key has the right format?

Try to remove the lines starting with ---- from your key and cert file.