1 package org.cacert.gigi.testUtils;
3 import java.security.KeyFactory;
4 import java.security.NoSuchAlgorithmException;
5 import java.security.PrivateKey;
6 import java.security.spec.InvalidKeySpecException;
7 import java.security.spec.PKCS8EncodedKeySpec;
8 import java.util.Base64;
11 public static PrivateKey parsePEMPrivateKey(String privKeyPEM) throws NoSuchAlgorithmException,
12 InvalidKeySpecException {
13 privKeyPEM = privKeyPEM.replace("-----BEGIN PRIVATE KEY-----", "").replace("\n", "");
14 // Remove the first and last lines
15 privKeyPEM = privKeyPEM.replace("-----END PRIVATE KEY-----", "");
17 // Base64 decode the data
18 byte[] encoded = Base64.getDecoder().decode(privKeyPEM);
20 // PKCS8 decode the encoded RSA private key
21 PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
22 KeyFactory kf = KeyFactory.getInstance("RSA");
23 PrivateKey privKey = kf.generatePrivate(keySpec);