Join GitHub today
GitHub is home to over 20 million developers working together to host and review code, manage projects, and build software together.
X509Cert.set_serial breaks for Certificate SerialNumbers with MSB=1 #7
in X509Cert.java line 303, set_serial makes a call to org.bouncycastle.x509.X509V3CertificateGenerator.setSerialNumber(BigInteger), which throws an exception if given a negative number.
During initialization, such a certificate with a serial number having MSB=1 can be loaded via java java.security.cert.X509Certificate (line 158), this results in cert.getSerialNumber() (line 166) to yield a negative BigInteger due to it's internal 2's complement representation. Thus, a valid certificate can result in an error.
Typically, such a situation might arise from a certificate authority which generates serial numbers via UID (random bit generation) instead of an incremental approach. This results in a ~50% chance that the MSB=1, and causing this failure.
The fix is simple, just make sure that the bouncycastle code does not receive a negative SerialNumber. This can be done by forcing BigInteger to interpret the serialNumber bits as positive number by setting the signum in the constructor, as follows:
note: This is difficult to reproduce using certificates generated via openssl CA, since it seems to pad the serial with extra 0s for MSB, neatly avoiding the problem.