Search code examples
javaandroidbouncycastlecsr

PKCS10CertificationRequest creation on android


I'm very new to android and java both, so hopefully I'm missing something easy here. All I want to do is create a simple PKCS10 certificate signing request. I have some code that will compile and run on my ubuntu box (java-6-openjdk), but throws a null pointer exception in the android emulator:

        KeyPair myKeyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
        X500Principal subject = new X500Principal("CN=Test V3 Certificate");
        PKCS10CertificationRequest csr = new PKCS10CertificationRequest
                        ( "SHA1withRSA",
                           subject,
                           myKeyPair.getPublic(),
                           null,
                           myKeyPair.getPrivate()
                );

        byte[] outBytes = csr.getEncoded();
        return new String(outBytes);

In the debugger I can see I have apparently constructed a PKCS10CertificationRequest, but I can't do anything with it (like getEncoded() or even toString()) without error. When I call getEncoded() it fails on the android emulator; this is the stack trace:

06-22 04:41:06.143: WARN/System.err(337): java.lang.NullPointerException: obj == null
06-22 04:41:06.213: WARN/System.err(337):     at org.bouncycastle.asn1.ASN1Collection.addObject(ASN1Collection.java:95)
06-22 04:41:06.353: WARN/System.err(337):     at org.bouncycastle.asn1.DERSequence.<init>(DERSequence.java:34)
06-22 04:41:06.433: WARN/System.err(337):     at org.bouncycastle.asn1.x509.AlgorithmIdentifier.toASN1Object(AlgorithmIdentifier.java:
124)
06-22 04:41:06.453: WARN/System.err(337):     at org.bouncycastle.asn1.ASN1Encodable.getDERObject(ASN1Encodable.java:
77)
06-22 04:41:06.483: WARN/System.err(337):     at org.bouncycastle.asn1.DEROutputStream.writeObject(DEROutputStream.java:
74)
06-22 04:41:06.523: WARN/System.err(337):     at org.bouncycastle.asn1.DERSequence.encode(DERSequence.java:70)
06-22 04:41:06.544: WARN/System.err(337):     at org.bouncycastle.asn1.DEROutputStream.writeObject(DEROutputStream.java:
74)
06-22 04:41:06.593: WARN/System.err(337):     at org.bouncycastle.jce.PKCS10CertificationRequest.getEncoded(PKCS10CertificationRequest.java:
443)

I've tried this with both the API levels 7 and 8. I know there's a ton of other details I could post about the versions of various components of my system. Like I said, I'm new to this, so right now I'm more looking for a direction to go in than necessarily a final answer.

Thanks very much,

Adam Mackler


Solution

  • You ran into a BouncyCastle bug. I am not sure it's fixed. I ended up using my own PKCS10CertificateRequest. You just need to change this one line in the constructor,

       this.sigAlgId = new AlgorithmIdentifier(sigOID, null);
    

    to

       this.sigAlgId = new AlgorithmIdentifier(sigOID);