title: Bouncycastle DER length IO error:
body: <p>This is my method:</p>
  
  <pre><code>import org.bouncycastle.asn1.ASN1InputStream;
  import java.io.ByteArrayInputStream;
  ...
  public static byte[] toDERBytes(byte[] data) throws IOException
  {
      ByteArrayInputStream inStream = new ByteArrayInputStream(data);
  
      //Uses imported bouncy castle library:
      ASN1InputStream asnInputStream = new ASN1InputStream(inStream);
      byte[] derArray = asnInputStream.readObject().getEncoded();
      asnInputStream.close();
  
      return derArray;
  }
  </code></pre>
  
  <p>According to the <a href="http://www.cs.berkeley.edu/~jonah/bc/org/bouncycastle/asn1/ASN1InputStream.html" rel="noreferrer">BouncyCastle documentation I have seen</a> ASN1InputStream.readobject() should actually get a DER object and not ASN1. (To my understanding DER is a subtype of ASN1)</p>
  
  <p>I then return the bytes.</p>
  
  <p>This works half the time, but the other half I get this error:</p>
  
  <pre><code>java.io.IOException: DER length more than 4 bytes: XXX
  </code></pre>
  
  <p>My questions are:</p>
  
  <ol>
  <li>Why do I only get the error SOMETIMES? (I always give it 65 bytes of data)</li>
  <li>How do I fix it?</li>
  <li>Am I DER encoding the right way?</li>
  </ol>