Java keystore with multiple keys and different pas

2019-04-15 05:22发布

问题:

i have created a java JKS keytore:

keytool -genkey -alias mydomain -keyalg RSA -keystore mytest.jks -keysize 2048

after that i created a P12 file, using the server's CRT with openssl:

openssl pkcs12 -export -in server.crt -inkey server.key > server.p12

now i imported the P12 file into my previously created JKS keystore:

keytool -importkeystore -srckeystore server.p12 -destkeystore mytest.jks -srcstoretype pkcs12

It works, i can use this JKS to initialize an SSL connection to the server:

public static SSLContext initSSLContext(String keystoreLocation, String keystorePwd, String truststorePwd, String serverCrtPwd)
SSLContext context;
context = SSLContext.getInstance("TLS");
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(keystoreLocation), keystorePwd.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, serverCrtPwd.toCharArray());

KeyStore trustStore = KeyStore.getInstance("jks");
trustStore.load(new FileInputStream(keystoreLocation), truststorePwd.toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);

context.init(kmf.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());

Putting the keystore location, password and the password for the imported CRT file in the parameters it works.

Now i have to convert and import multiple P12 files into the same JKS keystore, running the import part multiple times it works, i have multiple keys imported with different alias names and of course with different password. My problem is that now every imported keys have it own password. I would like to initialize the SSL connection only once with every available aliases from the given keystore. Because more server will send data to my application with SSL, they have different password, they are imported to my keystore but i cannot initialize my keystore with multiple passwords it accepts only one. How can i init my keystore with multiple imported P12 with different aliases and with different passwords? The init method accepts only one parameter for the "keys recovery from keystore".

Thanks!