Auxilio
Auxilio

Reputation: 41

CertificateFactory returns null with non-certificate input

I'm using java.security.cert.CertificateFactory to generate (from an InputStream), then verify a public certificate file. When I use a proper certificate file, ex cert.cert I get a proper certificate and can generate the fingerprint, use it for communication with a server, etc.

However, when I select files that are definitely not certificates, ex settings.txt I sometimes get a CertificateException and sometimes it actually null. I can't find a description of this behaviour for CertificateFactory, or any reasoning why some files cause generateCertificate to throw an exception vs. returning null.

My code in question:

CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
InputStream stream = new ByteArrayInputStream(parameters.getCertificate());
X509Certificate cert = (X509Certificate)certificateFactory.generateCertificate(stream);


The last line will either return the exception, or cert will be null. My question is:
Why does certificateFactory.generateCertificate(stream) return null when a non-certificate file is given as input? Shouldn't it throw a CertificateException?

Upvotes: 1

Views: 1595

Answers (1)

President James K. Polk
President James K. Polk

Reputation: 42009

I found this to be an interesting question. My reading of the CertificateFactory.generateCertificate() docs left one case unclear to me, what should be returned when the stream is positioned at EOF. I think it should generate an exception. I believe null should never be returned. The java.security.cert.CertificateFactory class itself simply delegates the generateCertificate() call to an internal spi class. OpenJDK8's implementation of this spi class never returns null. This is also likely true for Oracle's implementation. Therefore, I must conclude that you are not using one of these implementations.

When I examined the Bouncycastle provider's implementation, I see it returns null in several places, including when EOF is reached. It is possible that Bouncycastle's implementation is non-compliant.

Upvotes: 1

Related Questions