]> WPIA git - gigi.git/blobdiff - tests/org/cacert/gigi/testUtils/PemKey.java
Extract PEM I/O
[gigi.git] / tests / org / cacert / gigi / testUtils / PemKey.java
index 14d282fdce4e60c6566dea16a6ee908223589900..c790dd7250d45cd67ef2e104ddd3da1fa1b41b50 100644 (file)
@@ -1,5 +1,7 @@
 package org.cacert.gigi.testUtils;
 
+import java.io.IOException;
+import java.io.InputStreamReader;
 import java.security.KeyFactory;
 import java.security.NoSuchAlgorithmException;
 import java.security.PrivateKey;
@@ -8,19 +10,31 @@ import java.security.spec.PKCS8EncodedKeySpec;
 import java.util.Base64;
 
 public class PemKey {
-       public static PrivateKey parsePEMPrivateKey(String privKeyPEM) throws NoSuchAlgorithmException,
-               InvalidKeySpecException {
-               privKeyPEM = privKeyPEM.replaceAll("-----BEGIN (RSA )?PRIVATE KEY-----", "").replace("\n", "");
-               // Remove the first and last lines
-               privKeyPEM = privKeyPEM.replaceAll("-----END (RSA )?PRIVATE KEY-----", "");
 
-               // Base64 decode the data
-               byte[] encoded = Base64.getDecoder().decode(privKeyPEM);
+    public static PrivateKey parsePEMPrivateKey(String privKeyPEM) throws NoSuchAlgorithmException, InvalidKeySpecException {
+        if (privKeyPEM.startsWith("-----BEGIN RSA PRIVATE KEY-----")) {
+            // key is pkcs1 convert to p8
+            try {
+                Process p = Runtime.getRuntime().exec(new String[] {
+                        "openssl", "pkcs8", "-topk8", "-nocrypt"
+                });
+                p.getOutputStream().write(privKeyPEM.getBytes());
+                p.getOutputStream().close();
+                privKeyPEM = IOUtils.readURL(new InputStreamReader(p.getInputStream()));
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+        privKeyPEM = privKeyPEM.replaceAll("-----BEGIN PRIVATE KEY-----", "").replace("\n", "");
+        // Remove the first and last lines
+        privKeyPEM = privKeyPEM.replaceAll("-----END PRIVATE KEY-----", "");
+        // Base64 decode the data
+        byte[] encoded = Base64.getDecoder().decode(privKeyPEM);
 
-               // PKCS8 decode the encoded RSA private key
-               PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
-               KeyFactory kf = KeyFactory.getInstance("RSA");
-               PrivateKey privKey = kf.generatePrivate(keySpec);
-               return privKey;
-       }
+        // PKCS8 decode the encoded RSA private key
+        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
+        KeyFactory kf = KeyFactory.getInstance("RSA");
+        PrivateKey privKey = kf.generatePrivate(keySpec);
+        return privKey;
+    }
 }