How to retrieve X509 Certificate as “ds:X509Certificate” Data

I have seen that most the cases, You may need to retrieve the X509 Certificate as  <ds:X509Certificate> Data.  <ds:X509Certificate>  data can be seen in SOAP messages (SAML, WS-Security) that are passed  the security information.  You can easily retrieve X509Certificate data  using java  keytool command.

If you want to retrieve X509Certificate data from key store file (JKS)

keytool -export -keystore pathToKeystore -rfc -alias aliasNameForCertificate

If you want to retrieve X509Certificate data from certificate file ( .cert,  .pem and etc)

keytool -printcert -rfc -file pathToCertificate

Following is the output that I retrieve from wso2carbon certificate that contains in the WSO2 Carbon product

>keytool -printcert -rfc -file wso2.cert 

-----BEGIN CERTIFICATE----- 

MIICNTCCAZ6gAwIBAgIES343gjANBgkqhkiG9w0BAQUFADBVMQswCQYDVQQGEwJVUzELMAkGA1UE
CAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxDTALBgNVBAoMBFdTTzIxEjAQBgNVBAMMCWxv
Y2FsaG9zdDAeFw0xMDAyMTkwNzAyMjZaFw0zNTAyMTMwNzAyMjZaMFUxCzAJBgNVBAYTAlVTMQsw
CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzENMAsGA1UECgwEV1NPMjESMBAGA1UE
AwwJbG9jYWxob3N0MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCUp/oV1vWc8/TkQSiAvTou
sMzOM4asB2iltr2QKozni5aVFu818MpOLZIr8LMnTzWllJvvaA5RAAdpbECb+48FjbBe0hseUdN5
HpwvnH/DW8ZccGvk53I6Orq7hLCv1ZHtuOCokghz/ATrhyPq+QktMfXnRS4HrKGJTzxaCcU7OQID
AQABoxIwEDAOBgNVHQ8BAf8EBAMCBPAwDQYJKoZIhvcNAQEFBQADgYEAW5wPR7cr1LAdq+IrR44i
QlRG5ITCZXY9hI0PygLP2rHANh+PYfTmxbuOnykNGyhM6FjFLbW2uZHQTY1jMrPprjOrmyK5sjJR
O4d1DeGHT/YnIjs9JogRKv4XHECwLtIVdAbIdWHEtVZJyMSktcyysFcvuhPQK8Qc/E/Wq8uHSCo=
-----END CERTIFICATE-----

Also,  following is the simple java code that you can retrieve the certificate data as String from a give certificate file


 // build input stream using certificate file
 InputStream inputStream = new FileInputStream(filePath);

 // build X509Certificate object
 X509Certificate certificate = new X509CertImpl(inputStream);

 // get byte value of certificate
 byte[] value = certificate.getEncoded();

 // encode the value
 BASE64Encoder encoder=new BASE64Encoder();
 String encodedValue = encoder.encode(value);

Discuss this article on Stack Overflow

Leave a Reply

Your email address will not be published. Required fields are marked *