I have problem with loading certifiacate to key store. I can create that certificate in console with this command openssl pkcs12 -export -out cloudCA.p12 -inkey Cloud\ privateLey.key -in cloudCa.pem -certfile rootCa.pem -name "cloudCA"
I figured out how to load cloudCA.pem with privateKey.key but I can't find a way how to add there rootCA.pem. This is my current code. Thank 's for help.
//Regular patterns for certificate.
private static final Pattern CERT_PATTERN = Pattern.compile(
"-+BEGIN\\s+.*CERTIFICATE[^-]*-+(?:\\s|\\r|\\n)+" + // Header
"([a-z0-9+/=\\r\\n]+)" + // Base64 text
"-+END\\s+.*CERTIFICATE[^-]*-+", // Footer
CASE_INSENSITIVE);
private static final Pattern KEY_PATTERN = Pattern.compile(
"-+BEGIN\\s+.*PRIVATE\\s+KEY[^-]*-+(?:\\s|\\r|\\n)+" + // Header
"([a-z0-9+/=\\r\\n]+)" + // Base64 text
"-+END\\s+.*PRIVATE\\s+KEY[^-]*-+", // Footer
CASE_INSENSITIVE);
public static KeyStore loadKeyStore(String certificate, String privateKey, Optional<String> keyPassword)
throws IOException, GeneralSecurityException {
List<X509Certificate> certificateChain = readCertificateChain(certificate);
if (certificateChain.isEmpty()) {
throw new CertificateException("Certificate file string does not contain any certificates: ");
}
//Load and customize key string to byte array.
byte[] data = Base64.getDecoder().decode(privateKey.replace("\n","")
.replace("-----BEGIN RSA PRIVATE KEY-----", "")
.replace("-----END RSA PRIVATE KEY-----", "")
.replace(" ", ""));
/* Add PKCS#8 formatting */
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new ASN1Integer(0));
ASN1EncodableVector v2 = new ASN1EncodableVector();
v2.add(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.rsaEncryption.getId()));
v2.add(DERNull.INSTANCE);
v.add(new DERSequence(v2));
v.add(new DEROctetString(data));
ASN1Sequence seq = new DERSequence(v);
byte[] privKey = seq.getEncoded("DER");
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privKey);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey key = fact.generatePrivate(spec);
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null, null);
keyStore.setKeyEntry("CloudCA", key, keyPassword.orElse("").toCharArray(), certificateChain.stream().toArray(Certificate[]::new));
return keyStore;
}
private static List<X509Certificate> readCertificateChain(String contents) throws GeneralSecurityException {
Matcher matcher = CERT_PATTERN.matcher(contents);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
List<X509Certificate> certificates = new ArrayList<>();
int start = 0;
while (matcher.find(start)) {
byte[] buffer = Base64.getMimeDecoder().decode(matcher.group(1).getBytes(US_ASCII));
certificates.add((X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(buffer)));
start = matcher.end();
}
return certificates;
}