Skip to content

Instantly share code, notes, and snippets.

@lbalmaceda
Created June 15, 2018 14:32
Show Gist options
  • Save lbalmaceda/9a0c7890c2965826c04119dcfb1a5469 to your computer and use it in GitHub Desktop.
Save lbalmaceda/9a0c7890c2965826c04119dcfb1a5469 to your computer and use it in GitHub Desktop.
Pem Keys file reader for Java

Pem Keys File Reader (Java)

The PemUtils.java file contains a set of helper methods to read Pem Private or Public Keys from a given file. We make use of it in the tests of our Java-JWT library.

Dependencies

It only makes use of the Bouncy Castle (BC) library's PemReader and some Security classes from Java 7.

compile 'org.bouncycastle:bcprov-jdk15on:1.59'

How to use it

Read a Public Key

Call the readPublicKeyFromFile method passing the path to the file and the algorithm. Algorithm can be one of "RSA" or "EC".

RSAKey pubRSA = (RSAKey) PemUtils.readPublicKeyFromFile("/path/to/rsa/key.pem", "RSA")));
ECKey pubEC = (ECKey) PemUtils.readPublicKeyFromFile("/path/to/ec/key.pem", "EC")));

Read a Private Key

Call the readPrivateKeyFromFile method passing the path to the file and the algorithm. Algorithm can be one of "RSA" or "EC".

RSAKey privRSA = (RSAKey) PemUtils.readPrivateKeyFromFile("/path/to/rsa/key.pem", "RSA")));
ECKey privEC = (ECKey) PemUtils.readPrivateKeyFromFile("/path/to/ec/key.pem", "EC")));

LICENSE

MIT - https://opensource.org/licenses/MIT

//Copyright 2017 - https://github.com/lbalmaceda
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package com.auth0.jwt;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.EncodedKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class PemUtils {
private static byte[] parsePEMFile(File pemFile) throws IOException {
if (!pemFile.isFile() || !pemFile.exists()) {
throw new FileNotFoundException(String.format("The file '%s' doesn't exist.", pemFile.getAbsolutePath()));
}
PemReader reader = new PemReader(new FileReader(pemFile));
PemObject pemObject = reader.readPemObject();
byte[] content = pemObject.getContent();
reader.close();
return content;
}
private static PublicKey getPublicKey(byte[] keyBytes, String algorithm) {
PublicKey publicKey = null;
try {
KeyFactory kf = KeyFactory.getInstance(algorithm);
EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
publicKey = kf.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
System.out.println("Could not reconstruct the public key, the given algorithm could not be found.");
} catch (InvalidKeySpecException e) {
System.out.println("Could not reconstruct the public key");
}
return publicKey;
}
private static PrivateKey getPrivateKey(byte[] keyBytes, String algorithm) {
PrivateKey privateKey = null;
try {
KeyFactory kf = KeyFactory.getInstance(algorithm);
EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
privateKey = kf.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
System.out.println("Could not reconstruct the private key, the given algorithm could not be found.");
} catch (InvalidKeySpecException e) {
System.out.println("Could not reconstruct the private key");
}
return privateKey;
}
public static PublicKey readPublicKeyFromFile(String filepath, String algorithm) throws IOException {
byte[] bytes = PemUtils.parsePEMFile(new File(filepath));
return PemUtils.getPublicKey(bytes, algorithm);
}
public static PrivateKey readPrivateKeyFromFile(String filepath, String algorithm) throws IOException {
byte[] bytes = PemUtils.parsePEMFile(new File(filepath));
return PemUtils.getPrivateKey(bytes, algorithm);
}
}
@lbalmaceda
Copy link
Author

👋 @GabrielaElena we're currently using this in the tests for our java-jwt library, so I bet the error is on your key's format.

You can check for example usages here, a sample public key format here and a private one here. Note the version of the bouncy castle library being used here just in case.
I hope that helps.

@imuneer
Copy link

imuneer commented Aug 5, 2020

I am trying this with OpenSSL generated RSA file. I am getting Exception (InvalidKeyException).

Invalid Key: java.security.InvalidKeyException: IOException : algid parse error, not a sequence

But as @lbalmaceda said, it is working with the private key file he has shared above in the link.

I have generated RSA private key using OpenSSL with the following command
openssl genrsa -out private.key 1024

-----BEGIN RSA PRIVATE KEY-----
MIICXwIBAAKBgQC1POE0N0juIEKW4drJWaJ0dNtvSdG/H12cGO4qJRFgaZFUOn1s
pJ/gAw0nYJbQI89EJaH9DQwiesDq0XFkfMqRg01PdDWkEZe2QRP5++Nfmu+CI18P
kNDzbTdbGAw5Xfq/jrkjgdu+fJDz+QNS9VE5KEYe/m9sD91F9+r151qTRwIDAQAB
AoGBAJnrDC92TD+/sg3F3jNmJmvU2o9XGATCtJNfMNUmCe3hegUYb3CXFxf+P2uT
wkEeSGZNt5bbP9UAf1ptaWm3+afQ1h83CPOQhLl8r4/6buTfIZL2eV+C9gPOwlBa
gRsznGh4qg8D/P/X8Mq6+Q4eHiIDdP6/HjDuVAfPY8KlEoDhAkEA3oAA6mqge+Xi
1Otj+F9TVSKA6jfMFbHmwOEHi3ACB93BMMqaCaxSV6T9MKLtttLJTP1wBx+CdQte
tcLlxrbTaQJBANCGeVYHfrKpO+O0U1R2nIEWJ7Pd8oTITulyI55W2PqC05rYai7u
6Q26YMsjIlMubqv6UzuVReV03RidmVPKSy8CQQC97ZhaghBiErdRN2oLzxtsVdqj
lGOitUybort0/HTPUC0kQB3DWhSj+hOi28F9SWtKTCDAA9axoLYFA8xulwvZAkEA
y4BQ7cpGtWk/T0tuf2F5/uh2Oq0BvuAVUvHXHPG4s1H13IoTplX2DzWyvMw+9Vq9
Gw0jKWTWX8Ya96jmN8WWdQJBALjiR19s7+PBc8iQE0WHsoU1rpZglyglifg2P7hz
yEmLuocXDc96Ftvnq8NvZhQpyZEnMtMmt99qki+DCDdwf20=
-----END RSA PRIVATE KEY-----

and is validated with OpenSSL without any issue.

The only difference between the example file and my file is, in example it says "-----BEGIN PRIVATE KEY-----" and in my one "-----BEGIN RSA PRIVATE KEY-----"

@massenz
Copy link

massenz commented Sep 4, 2020

Thanks for this; it works, however, I found I needed to do some mangling with EC keys:

    // See this: https://github.com/auth0/java-jwt/issues/270
    // Keys generated with:
    //    openssl ecparam -name prime256v1 -genkey -noout -out ec-key.pem                      
    //    openssl pkcs8 -topk8 -inform pem -in ec-key.pem -outform pem -nocrypt -out ec-key-1.pem

The first line is taken from auth0 example in the JWT e-book, and there is probably a better way to generate the key directly in PKCS#8 format, but this works and it's good enough for me.

I have modified your PemUtils class so an not to "swallow" the exception error, but log it (from there to Google it, was a simple step :) ); also, not sure I'd "silently" swallow it to return null, a re-throw may be in order.

But that's details, thanks again for sharing.

@edwardsteven
Copy link

edwardsteven commented Jul 18, 2021

Hey all,
I ran into the same problem - it turns out the RSA PRIVATE KEY and PRIVATE KEY are different types (PKCS8 vs PKCS1). This gist only covers the PKCS8 scenario: the following will allow you to read a PKCS1; use the readPKCS1PrivateKeyFromFile method instead of the original for your private key.

 private static PrivateKey getPKCS1PrivateKey(byte[] keyBytes, String algorithm) {
        PrivateKey privateKey = null;
        try {
            RSAPrivateKey asn1PrivKey = RSAPrivateKey.getInstance(ASN1Sequence.fromByteArray(keyBytes));
            RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(asn1PrivKey.getModulus(), asn1PrivKey.getPrivateExponent());
            KeyFactory kf = KeyFactory.getInstance(algorithm);
            privateKey = kf.generatePrivate(rsaPrivateKeySpec);
        } catch (NoSuchAlgorithmException e) {
            System.out.println("Could not reconstruct the private key, the given algorithm could not be found.");
        } catch (InvalidKeySpecException e) {
            System.out.println("Could not reconstruct the private key");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return privateKey;
    }

public static PrivateKey readPKCS1PrivateKeyFromFile(String filepath, String algorithm) throws IOException {
        byte[] bytes = PemUtils.parsePEMFile(new File(filepath));
        return PemUtils.getPrivateKey(bytes, algorithm);
    }

@Elanza-48
Copy link

checkout this article for EC generator: https://connect2id.com/products/nimbus-jose-jwt/openssl-key-generation
this works well for me. No need to generate extra publlic key form the private.pem and also no need to convert pkcs#1 to pkcs#8.

@rgoncami
Copy link

rgoncami commented Dec 29, 2021

I have a question here:

RSAKey pubRSA = (RSAKey) PemUtils.readPublicKeyFromFile("/path/to/rsa/key.pem", "RSA")));

This path/to/rsa... is the absolute path? Such as: "C:\\Users\\7700668141\\dev\\api-migration\\src\\main\\java\\br\\com\\foo\\bar\\app\\keys\\PublicKey.pem"?

@clydebarrow
Copy link

Reading an EC private key, for example to use with ES256 signing of a JWT, is as simple as this:

In build.gradle.kts:

     implementation("org.bouncycastle":bcpkix-jdk15on:1.70")

Read a key from a string:

import org.bouncycastle.asn1.pkcs.PrivateKeyInfo
import org.bouncycastle.openssl.PEMParser
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter
import java.io.StringReader
import java.security.interfaces.ECPrivateKey

    val pemKey = PEMParser(StringReader(privateKeyString)).readObject() as PrivateKeyInfo
    val ecKey = JcaPEMKeyConverter().getPrivateKey(pemKey) as ECPrivateKey

@ShaneLee
Copy link

ShaneLee commented Aug 4, 2022

Thanks for this

If anyone is experiencing the issue with the NullPointer from readPemObject() returning null it's worth checking the 'begin' and 'end' portions of your key. The bouncy castle library doing the reading requires 5 dashes with no space between them an 'BEGIN' or 'END'

e.g

-----BEGIN PUBLIC KEY-----

not
----- BEGIN PUBLIC KEY-----

and not (4 dashes here)

----BEGIN PUBLIC KEY ----

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment