How to use Java code to automatically Import SSL certificates to Java's key storage file (keystore), sslkeystore
In the process of developing or using SSL, many software products need to provide java keystore, especially some Java-based middleware Products.
The general practice is to use the built-in JDK tool command (keytool), for example, the following example
Keytool-import-v-alias EnTrust2048-file D: \ certs \ EnTrust2048.cer-keystore D: \ certs \ test. jks
Keytool-import-v-alias EntrustCertificationAuthorityL1C-file D: \ certs \ entrustcertifauthorityl1c. cer-keystore D: \ certs \ test. jks
Keytool-import-v-alias test.com-file D: \ certs \ Service-now.com.cer-keystore D: \ certs \ test. jks
However, this method is cumbersome. Suppose we have 100 SSL certificates under a folder, then we need to enter 100 similar to the above command. For folders
There is a certificate in it, which is more troublesome. Is there a good way? I will share with you how to implement it using java program code.
import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.security.KeyStore;import java.security.cert.CertificateFactory;import java.security.cert.X509Certificate;import java.util.List;import javax.naming.ldap.LdapName;import javax.naming.ldap.Rdn;import javax.security.auth.x500.X500Principal;public class KeyStoreHelper {public static void createTrustJKSKeyStore(final String originalTrustFolder,final String jksTrustStoreLocation, final String password) {File keyStoreFile = new File(jksTrustStoreLocation);if (!keyStoreFile.exists()) {try {KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());keystore.load(null, password.toCharArray());File trustedFolder = new File(originalTrustFolder);File[] certs = trustedFolder.listFiles();if (certs != null) {for (File cert : certs) {CertificateFactory factory = CertificateFactory.getInstance("X.509");try {X509Certificate certificate = (X509Certificate) factory.generateCertificate(new FileInputStream(cert));X500Principal principal = certificate.getSubjectX500Principal();LdapName ldapDN = new LdapName(principal.getName());List<Rdn> rdns = ldapDN.getRdns(); for (Rdn rdn : rdns) {String type = rdn.getType();if (type.equals("CN")) { keystore.setCertificateEntry((String) rdn.getValue(),certificate); break;} }} catch (Exception ex) {continue; }} }FileOutputStream fos = new FileOutputStream(jksTrustStoreLocation);keystore.store(fos, password.toCharArray());fos.close();} catch (Exception exp) {}}}/** * @param args */public static void main(String[] args) {KeyStoreHelper.createTrustJKSKeyStore("D:\\cacerts", "D:\\cacerts\\test.jks", "test123");}}
The above Java class can help us do this. At the same time, we can develop a visual program using this help method, which is more convenient, that is, an Eclipse Plugin plug-in developed by the author.
Interface design.