Java: read public key files in PEM format 

Joined:
04/09/2007
Posts:
784

October 31, 2013 18:17:09    Last update: October 31, 2013 18:17:09
You have a PGP public in PEM format, which cannot be stored in a Java key store. But you have the PEM encoded public key file. This class reads the file and creates a public key class in Java.

Example key file:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzn34Tjjn8ngKRToZGi7A
o5xeqJGDatvk9oEdRuDUEEfstKubN6UPRph5sPGNYXkdVXQDv8GQDZQo1+8PSGuq
zClm9boFZSVkAmEWlFe2tYH7WQbZtM4gY0tameBoFHH1l8NpQlEXXBKn7Hj1O7xN
EmiriS/5xDUstFmH5jQo/Q9cLh596Y3zK62ucScAt0iKMWT0h6XbLbRlCzPDmwyi
9VSbSYieZLsRcWKQ5d6nzJ3GFjwnWfx/OtryhtCQp8a8Z5luJWzyFgR+575WTQDf
N4o6fu8KOptHhrGr1QI0Irqqi/+GrWmpENPmKDkrxWHzia+2zKuNB0vp8fHwwMH2
xwIDAQAB
-----END PUBLIC KEY-----


Java code:
import java.io.*;
import java.security.*;
import java.security.spec.*;

import sun.misc.BASE64Decoder;

public class ReadPublicKey {
    public static void main(String[] args) throws Exception {
	// read key bytes
	FileInputStream in = new FileInputStream("mykey.pem.pub");
	byte[] keyBytes = new byte[in.available()];
	in.read(keyBytes);
	in.close();

	String pubKey = new String(keyBytes, "UTF-8");
	pubKey = pubKey.replaceAll("(-+BEGIN PUBLIC KEY-+\\r?\\n|-+END PUBLIC KEY-+\\r?\\n?)", "");

	// don't use this for real projects!
	BASE64Decoder decoder = new BASE64Decoder();
	keyBytes = decoder.decodeBuffer(pubKey);

	// generate public key
	X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
	KeyFactory keyFactory = KeyFactory.getInstance("RSA");
	PublicKey publicKey = keyFactory.generatePublic(spec);

	System.out.println(
	    String.format("Key format: %s, algorithm: %s",
		    publicKey.getFormat(),
		    publicKey.getAlgorithm()));
    }
}
Share |
| Comment  | Tags