Creating keystore file programmatically

Hi,

Wondering if you will be able to help me. I would like to find out how you can create a keystore file programmatically without using the keytool command.

What I'm trying to do is generate KeyPairs for the SSL connections. After the keys are signed, I would like to insert the keys into a new keystore file. Is that possible and if it is do you perhaps know how?

Thanks

Julia

[412 byte] By [jewelkuoa] at [2007-9-28 3:55:40]
# 1

Hi Julia,

keytool does not allow you to import private keys into a keystore but, I bypassed this problem this way:

after creating your key pair convert them into the pkcs12 format

openssl pkcs12 -inkey privatekey.key -in certificate.crt -export -out somename.p12

fortunately using the following code that was already posted in the forum, you will be able to create a new keystore with your private key :)

import java.security.*;

import java.io.*;

// assumes you are using a 3rd party keystore library

// for pkcs12 key stores. For some reason, JDK 1.4 won't

// read pkcs12 files exported from MIE / Netscape

class Convert {

static public void main(String[] args) throws Exception {

try {

//pkcs12 keystore

KeyStore ks = KeyStore.getInstance("pkcs12");

//jks keystore

KeyStore ks2 = KeyStore.getInstance("jks");

// load the pkcs12 file

ks.load(new FileInputStream("C:\\insurance.p12"),"insurance123".toCharArray());

// load the jks file (have to have an existing one)

ks2.load(new FileInputStream("C:\\.temp"),"temp123".toCharArray());

//read the p12 certificate

java.security.cert.Certificate [] cc = ks.getCertificateChain("1");

//gets the private key having as alias "1" and as password "insurance123"

Key k = ks.getKey("1", "insurance123".toCharArray());

// add to keystore and save

ks2.setKeyEntry("insurance", k, "insurance123".toCharArray(),cc);

FileOutputStream out = new FileOutputStream("C:\\newstore.keystore");

ks2.store(out, "insurance123".toCharArray());

out.close();

} catch (Throwable e) { e.printStackTrace(); } }

} //end of the class

the following call:

ks2.load(new FileInputStream("C:\\.temp"),"temp123".toCharArray());

assumes that you already created a keystore (.temp) having for password : temp123

Hope this help :)

KAnis

KAnisa at 2007-7-7 23:27:48 > top of Java-index,Security,Java Secure Socket Extension (JSSE)...