Search code examples
javaexceptionbouncycastle

Why does ASN1Object.getEncoded() throw IOException in BouncyCastle?


ASN1Object (and all classes that inherit it) has a getEncoded() method that is supposed to return the DER/BER encoding. However it's marked as throwing an IOException.

I expected the encoding to be done in memory and no IO to be performed. Furthermore, this complicates the surrounding code by requiring throws or try catches.

Why is the throws IOException there?


Solution

  • ASN1Object.getEncoded

    public byte[] getEncoded()
        throws IOException
    {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        ASN1OutputStream      aOut = new ASN1OutputStream(bOut);
    
        aOut.writeObject(this); // This is where the throws happens.
    
        return bOut.toByteArray();
    }
    

    ASN1OutputStream.writeObject:

    public void writeObject(
        ASN1Encodable obj)
        throws IOException
    {
        if (obj != null)
        {
            obj.toASN1Primitive().encode(this);
        }
        else
        {
            throw new IOException("null object detected");
        }
    }
    

    Unless a child class has overriden getEncoded, an IOException in this context means one or more of the objects involved were null.