1

I'm getting the following error when trying to generate an X509 certificate on android

java.lang.NullPointerException: Attempt to invoke virtual method 'java.security.PublicKey java.security.cert.X509Certificate.getPublicKey()' on a null object reference

Below is the code I use to achieve this:

            AssetFileDescriptor assetFileDescriptor = this.getAssets().openFd("cert.cer");
        FileDescriptor securityCertificate = assetFileDescriptor.getFileDescriptor();

        FileInputStream fin = new FileInputStream(securityCertificate);
        CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
        X509Certificate certificate = (X509Certificate) cf.generateCertificate(fin);

The error seem to be happening on cf.generateCertificate(fin)

Noel Omondi
  • 551
  • 1
  • 6
  • 23
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – pvg Nov 12 '17 at 19:43
  • 1
    No, its not a duplicate of that, I tried checking if the FileInputStream and CertificateFactory if they are null before using them to generate the X509, but they aren't, the method generateCertificate() returns null and this is not my method – Noel Omondi Nov 12 '17 at 19:46
  • Is cf != null after CertificateFactory.getInstance() call? Are you sure the parameter it is X.509 instead of X509? – Juan Nov 12 '17 at 19:47
  • If `generateCertificate` returns null why are you getting an NPE? Post your full exception and the line that generates it. – pvg Nov 12 '17 at 19:47

1 Answers1

1

Managed to solve this by using InputStream instead of FileInputStream, the code below works fine for me:

        InputStream inputStream = assetManager.open("cert.cer");
        CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
        X509Certificate certificate = (X509Certificate) cf.generateCertificate(inputStream);
Noel Omondi
  • 551
  • 1
  • 6
  • 23