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;
public class PemKey {
public static PrivateKey parsePEMPrivateKey(String privKeyPEM) throws NoSuchAlgorithmException,
InvalidKeySpecException {
- privKeyPEM = privKeyPEM.replace("-----BEGIN PRIVATE KEY-----", "").replace("\n", "");
+ 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.replace("-----END PRIVATE KEY-----", "");
-
+ privKeyPEM = privKeyPEM.replaceAll("-----END PRIVATE KEY-----", "");
+ System.out.println(privKeyPEM);
// Base64 decode the data
byte[] encoded = Base64.getDecoder().decode(privKeyPEM);