Skip to content

Instantly share code, notes, and snippets.

@thedevappsecguy
Forked from lbalmaceda/PemUtils.java
Created August 14, 2021 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thedevappsecguy/bf946e20f00cb785481a21b0b4ccf8d2 to your computer and use it in GitHub Desktop.
Save thedevappsecguy/bf946e20f00cb785481a21b0b4ccf8d2 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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment