简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM