]> WPIA git - gigi.git/blob - tests/org/cacert/gigi/testUtils/PemKey.java
Certificate testCase fix error on mac.
[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         public static PrivateKey parsePEMPrivateKey(String privKeyPEM) throws NoSuchAlgorithmException,
14                 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[] { "openssl", "pkcs8", "-topk8", "-nocrypt" });
19                                 p.getOutputStream().write(privKeyPEM.getBytes());
20                                 p.getOutputStream().close();
21                                 privKeyPEM = IOUtils.readURL(new InputStreamReader(p.getInputStream()));
22                         } catch (IOException e) {
23                                 e.printStackTrace();
24                         }
25                 }
26                 privKeyPEM = privKeyPEM.replaceAll("-----BEGIN PRIVATE KEY-----", "").replace("\n", "");
27                 // Remove the first and last lines
28                 privKeyPEM = privKeyPEM.replaceAll("-----END PRIVATE KEY-----", "");
29                 System.out.println(privKeyPEM);
30                 // Base64 decode the data
31                 byte[] encoded = Base64.getDecoder().decode(privKeyPEM);
32
33                 // PKCS8 decode the encoded RSA private key
34                 PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
35                 KeyFactory kf = KeyFactory.getInstance("RSA");
36                 PrivateKey privKey = kf.generatePrivate(keySpec);
37                 return privKey;
38         }
39 }