Programmatically Import CA trust cert into existing keystore file without using keytool

我与影子孤独终老i 提交于 2019-11-27 00:57:59

I have solve the Question.Here's the code

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.io.IOException;
import java.io.InputStream;
import java.io.DataInputStream;
import java.io.ByteArrayInputStream;
import java.security.spec.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.Collection;

public class ImportCA {
public static void main(String[] argv) throws Exception {

String certfile = "yourcert.cer"; /*your cert path*/
FileInputStream is = new FileInputStream("yourKeyStore.keystore");

KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(is, "yourKeyStorePass".toCharArray());

String alias = "youralias";
char[] password = "yourKeyStorePass".toCharArray();

//////

CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream certstream = fullStream (certfile);
Certificate certs =  cf.generateCertificate(certstream);

///
File keystoreFile = new File("yourKeyStorePass.keystore");
// Load the keystore contents
FileInputStream in = new FileInputStream(keystoreFile);
keystore.load(in, password);
in.close();

// Add the certificate
keystore.setCertificateEntry(alias, certs);

// Save the new keystore contents
FileOutputStream out = new FileOutputStream(keystoreFile);
keystore.store(out, password);
out.close();

}

private static InputStream fullStream ( String fname ) throws IOException {
    FileInputStream fis = new FileInputStream(fname);
    DataInputStream dis = new DataInputStream(fis);
    byte[] bytes = new byte[dis.available()];
    dis.readFully(bytes);
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    return bais;
}
}

Hope can help those people that need it. It's just a simple code that insert the .cer file CA cert into your keystore without using keytool in CMD =)

Download certs from links and store into specific path.. then load that file into trustStore during runtime using below code.. i hope this exaple will help you..

KeyStore keyStore = KeyStore.getInstance("JKS");
String fileName = "D:\\certs_path\\cacerts"; // cerrtification file path
System.setProperty("javax.net.ssl.trustStore", fileName);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!