Java: read private key files in PEM format  

Joined:
04/09/2007
Posts:
784

November 01, 2013 10:17:57    Last update: November 01, 2013 10:17:57
This example class reads a RSA private key file in PEM format.
import java.io.*;
import java.security.*;
import java.security.spec.*;

import sun.misc.BASE64Decoder;

public class ReadPrivateKey {
    public static void main(String[] args) throws Exception {
        PrivateKey key = readPrivateKey(new File("mykey"));
    }

    public static PrivateKey readPrivateKey(File keyFile) throws Exception {
    	// read key bytes
	FileInputStream in = new FileInputStream(keyFile);
	byte[] keyBytes = new byte[in.available()];
	in.read(keyBytes);
	in.close();

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

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

	// generate private key
	PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
	KeyFactory keyFactory = KeyFactory.getInstance("RSA");
	return keyFactory.generatePrivate(spec);
    }
}
Share |
| Comment  | Tags