Saturday, 28 March 2009

X509 certificate

This post shows how to generate a x509 certificate using keytool (jdk/bin), and import it from C#.

1) Use keytool to generate the public key, specifying for example keytool -genkeypair etc... -keyalg RSA -keysize 1024
2) Export the key into a X509 certificate: keytool -exportcert etc.. -rfc -file itsc.cer

If this works, on Windows, you can double-click on itsc.cer and you will see a nice window with the certificate information.

In C#, to import the certificate:

var streamReader = new StreamReader(@".....\itsc.cer");
string x509Str = streamReader.ReadToEnd();
var x509Certificate = new X509Certificate2(Encoding.UTF8.GetBytes(x509Str));
RSACryptoServiceProvider rsaCryptoServiceProvider = (RSACryptoServiceProvider)x509Certificate.PublicKey.Key;

Back to Java.

What you need to do is to extract by code the private key from the keystore:

KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(new FileInputStream(keyStorePath), "your password".toCharArray());
Key key = keyStore.getKey("your alias", "your password".toCharArray());

No comments:

Blog Archive