In the process of developing or using SSL, a lot of software needs us to provide Java KeyStore, especially some Java-based middleware products.
Our usual practice is that the JDK comes with a tool command (Keytool) to do, 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\EntrustCertificationAuthorityL1C.cer- KeyStore D:\certs\test.jks
Keytool-import-v-alias test.com-file D:\certs\Service-now.com.cer-keystore D:\certs\test.jks
But this is cumbersome, assuming we have a folder under the 100 SSL certificate, then we will enter 100 similar to the above command. If it is a folder inside a nested folder
There is also a certificate inside, it is more troublesome. So is there a good way? I would like to share with you how to use Java program code to achieve.
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); 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 = Certifi Catefactory.getinstance ("n"); 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.getv Alue (), 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.createtrustjkskeystor E ("D:\\cacerts", "D:\\cacerts\\test.jks", "test123");}}
The above Java class can help us do this thing. At the same time we can also put this help method to develop a visual program, which is more convenient, is the author's own development of an Eclipse plugin plug-in
Interface design.
How to use Java code to automatically import SSL certificates into the Java KeyStore file (keystore)