Missing leading zeroes while retrieving serial number of a x509 cert

懵懂的女人 提交于 2019-12-20 07:47:49

问题


I'm trying to get serial number from a X.509 Cert.. When i compare the Serial number generated by my code with the actual serial number(on windows), leading zeroes of the actual serial number(of the X509 cert) are missing.

Any suggestions or alternative ways to get the serial number of the x.509 cert in hex with the leading zeroes??

Below is the code segment which I'm currently using:

InputStream in = new FileInputStream("cert");
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(in);
String serialNum = certificate.getSerialNumber().toString(16);
System.out.println(serialNum);

回答1:


BigInteger has a toByteArray() method that re-adds the leading 00s:

byte[] serialNumBA = certificate.getSerialNumber().toByteArray()

Now you have several ways to convert the byte array to a hex string:

How to convert a byte array to a hex string in Java?

For example with Apache commons codec:

String serialNum = Hex.encodeHexString(serialNumBA);


来源:https://stackoverflow.com/questions/41031770/missing-leading-zeroes-while-retrieving-serial-number-of-a-x509-cert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!