Wednesday, March 19, 2008

how to find out the version of X.509 certificate? (v1, v2 or v3)

At times, we require to find out the version of given X.509 certificate, whether it is v1, v2 or v3 type certificate. A key differentiator between version v1 and v3 is that v3 certificate have extensions, which v1 doesn't have. But, at times, it's difficult to know whether any extensions are there or not, or if information like Email Address are there, can you consider them as extension or not?

OpenSSL and Java SE 6 utility tool 'keytool' [1] from Sun Microsystem creates X509v3 certificates, whereas Java SE 5 or earlier keytool creates X509v1 certificate. Keytool can import and export v1, v2 and v3 certificates from keystores.

If you don't remember, or else you received certificates from some other source, then you can figure out using following,
Programming Approach: Use X509Certificate[2] interface to get access to extensions and version number.
try { // Load the keystore
File file = new File("mykeystore.jks");
FileInputStream is = new FileInputStream(file);
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
// List the aliases
Enumeration enum = keystore.aliases();
for (; enum.hasMoreElements(); ) {
String alias = (String)enum.nextElement();
java.security.cert.Certificate cert = keystore.getCertificate(alias);
if (cert instanceof X509Certificate) {
X509Certificate x509cert = (X509Certificate)cert;
// Get Version no {X509CertInfo class gives version num starting from zero, hence if you get '2', it 's actually X.509 v3 certificate}
x509cert.getVersion();
// Get subject
Principal principal = x509cert.getSubjectDN();
String subjectDn = principal.getName();
// Get issuer
principal = x509cert.getIssuerDN();
String issuerDn = principal.getName();
}
}
} catch (java.security.cert.CertificateException e) {
} catch (NoSuchAlgorithmException e) {
} catch (FileNotFoundException e) { // Keystore does not exist
} catch (KeyStoreException e) {
} catch (IOException e) {
}

Use OpenSSL: Download and install OpenSSL [3] pre built binaries for Windows.


  • Export the certificate to .CER format from the keytool -export command: keytool -export -alias myalias -file MYCERT.cer -keystore mykeystore -storepass mystorepassword
  • Convert CER format to PEM format using openssl command: x509 -inform der -in MYCERT.cer -out MYCERT.pem
  • Check the version using openssl command: x509 -in MYCERT.pem -inform PEM -text
You can see following information along with Validity, Subject, Subject Public Key Info and Certificate:
Certificate:
Data:
Version: 1 or 2 or 3
Serial Number: .....
Signature Algorithm: .....

Till now, you must have figured out what's the version of the X.509 certificate you are using. :)

[1]. http://java.sun.com/javase/6/docs/technotes/tools/solaris/keytool.html
[2]. http://java.sun.com/j2se/1.4.2/docs/api/java/security/cert/X509Certificate.html
[3]. http://www.openssl.org/related/binaries.html