Skip to content

Instantly share code, notes, and snippets.

@lbalmaceda
Created June 15, 2018 14:32
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • 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);
}
}
@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