Centaur Tech

Dips

Friday, May 22

x.509 issue

Trying to generate an x509 certificate object from a byte stream :

    byte[] certBytes = (byte[]) certificatestring.getBytes();

    ByteArrayInputStream bin = new ByteArrayInputStream(certBytes);

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    X509Certificate certificate = (X509Certificate) cf.generateCertificate(bin);

It was giving me following exception :

java.security.cert.CertificateParsingException: invalid DER-encoded certificate data
 at sun.security.x509.X509CertImpl.parse(X509CertImpl.java:1680)
 at sun.security.x509.X509CertImpl.(X509CertImpl.java:303)
 at sun.security.provider.X509Factory.engineGenerateCertificate(X509Factory.java:104)
 at java.security.cert.CertificateFactory.generateCertificate(CertificateFactory.java:271)
The same certificate if I loaded from a saved .cer file, was working perfectly fine. It seemed like it was an issue with different kind of input streams. I checked for source code (thank heavens for open source !) at http://www.java2s.com/Open-Source/Java-Document/6.0-JDK-Modules-sun/security/sun/security/provider/X509Factory.java.htm and it seemed that there are 2 types of encoding it expects :
Base64 - if the inputstream starts with "-----BEGIN"
DER - if does not starts with above.
 
The bytestream which I had read from ldap needed to be appended with "-----BEGIN CERTIFICATE-----\n" and at the end with "\n-----END CERTIFICATE-----"
The certstring looked something like (valid one):
-----BEGIN CERTIFICATE-----
MIICYDCCAgqgAwIBAgIQBuJwHCWs3BMk7g16aheAGDANBgkqhkiG9w0BAQQFADBP
MSIwIAYDVQQKExlGaXJzdCBVbmlvbiBOYXRpb25hbCBCYW5rMSkwJwYDVQQLEyBD
b21tZXJjaWFsIENlcnRpZmljYXRlIEF1dGhvcml0eTAeFw05OTA5MTIwMDAwMDBa
Fw0wMDA5MTEyMzU5NTlaMIGZMSIwIAYDVQQKFBlGaXJzdCBVbmlvbiBOYXRpb25h
bCBCYW5rMSkwJwYDVQQLFCBDb21tZXJjaWFsIENlcnRpZmljYXRlIEF1dGhvcml0
eTEYMBYGA1UECxMPVVNFUklEIC0gd2xmYWRtMRYwFAYDVQQDEw13bGZhZG0gd2xm
YWRtMRYwFAYJKoZIhvcNAQkBFgdpQGkubmV0MIGfMA0GCSqGSIb3DQEBAQUAA4GN
ADCBiQKBgQDC8Y/pbxTPmCd+eEyXWtMnlBhXwGbTyc41VQd3g74jn31AvFFJ3f9P
0ZFw+rN2+IP2nUhn2EfyzskY7P7VsohKRCXxoovMSeIdXib3414S6jfhRXCMbUdA
PNQi5TyByfSKaf/VBwypufU52ERq/pBzpm2ktREii7btmt+8I109wwIDAQABozMw
MTAJBgNVHRMEAjAAMBEGCWCGSAGG+EIBAQQEAwIHgDARBgpghkgBhvhFAQYJBAMB
Af8wDQYJKoZIhvcNAQEEBQADQQCjF+Vy7JHEIVAasDnw62j3hi6FhgDRVOgaEEbb
BoaGVCSAAibNX4V02b+LOfDYXaJVpipFEiYiX5QE+Eht0i/s
-----END CERTIFICATE-----
This should create that x509 object for you in a ziffy !

Dips at 5:51 AM

0 comments

0 Comments

Post a Comment