]> WPIA git - gigi.git/blob - tests/org/cacert/gigi/testUtils/PemKey.java
c790dd7250d45cd67ef2e104ddd3da1fa1b41b50
[gigi.git] / tests / org / cacert / gigi / testUtils / PemKey.java
1 package org.cacert.gigi.testUtils;
2
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;
11
12 public class PemKey {
13
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
17             try {
18                 Process p = Runtime.getRuntime().exec(new String[] {
19                         "openssl", "pkcs8", "-topk8", "-nocrypt"
20                 });
21                 p.getOutputStream().write(privKeyPEM.getBytes());
22                 p.getOutputStream().close();
23                 privKeyPEM = IOUtils.readURL(new InputStreamReader(p.getInputStream()));
24             } catch (IOException e) {
25                 e.printStackTrace();
26             }
27         }
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);
33
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);
38         return privKey;
39     }
40 }