1 package org.cacert.gigi.testUtils;
3 import java.io.IOException;
4 import java.io.InputStreamReader;
5 import java.security.KeyFactory;
6 import java.security.NoSuchAlgorithmException;
7 import java.security.PrivateKey;
8 import java.security.spec.InvalidKeySpecException;
9 import java.security.spec.PKCS8EncodedKeySpec;
10 import java.util.Base64;
14 public static PrivateKey parsePEMPrivateKey(String privKeyPEM) throws NoSuchAlgorithmException, InvalidKeySpecException {
15 if (privKeyPEM.startsWith("-----BEGIN RSA PRIVATE KEY-----")) {
16 // key is pkcs1 convert to p8
18 Process p = Runtime.getRuntime().exec(new String[] {
19 "openssl", "pkcs8", "-topk8", "-nocrypt"
21 p.getOutputStream().write(privKeyPEM.getBytes());
22 p.getOutputStream().close();
23 privKeyPEM = IOUtils.readURL(new InputStreamReader(p.getInputStream()));
24 } catch (IOException e) {
28 privKeyPEM = privKeyPEM.replaceAll("-----BEGIN PRIVATE KEY-----", "").replace("\n", "");
29 // Remove the first and last lines
30 privKeyPEM = privKeyPEM.replaceAll("-----END PRIVATE KEY-----", "");
31 // Base64 decode the data
32 byte[] encoded = Base64.getDecoder().decode(privKeyPEM);
34 // PKCS8 decode the encoded RSA private key
35 PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
36 KeyFactory kf = KeyFactory.getInstance("RSA");
37 PrivateKey privKey = kf.generatePrivate(keySpec);