一、服务端pem转KeyStore
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");FileInputStream caInputStream = new FileInputStream(caPath);List<X509Certificate> caList = certificateFactory.generateCertificates(caInputStream).stream().map(v->(X509Certificate)v).collect(Collectors.toList());KeyStore keystore = KeyStore.getInstance("JKS");keystore.load(null, null);for(X509Certificate ca: caList)keystore.setCertificateEntry(ca.getSubjectDN().getName(), ca);
二、带有私key的客户端pem转KeyStore
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");FileInputStream caInputStream = new FileInputStream(caPath);List<X509Certificate> caList = certificateFactory.generateCertificates(caInputStream).stream().map(v->(X509Certificate)v).collect(Collectors.toList());KeyStore keystore = KeyStore.getInstance("JKS");keystore.load(null, null);privateKeyBase64 = privateKeyBase64.replace("-----BEGIN PRIVATE KEY-----", "").replace("\n", "").replace("-----END PRIVATE KEY-----", "");byte[] privateKeyBytes = Base64.decodeBase64(privateKeyBase64.getBytes(StandardCharsets.UTF_8));KeyFactory keyFactory = KeyFactory.getInstance("RSA");KeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);keystore.setKeyEntry("alias", privateKey, password.toCharArray(), caList.toArray(new X509Certificate[caList.size()]));
三、KeyStore转jks文件
try(FileOutputStream outputStream = new FileOutputStream("crt.jks")) {keystore.store(outputStream, password.toCharArray());}