This is my method:
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;
}
According to the BouncyCastle documentation I have seen ASN1InputStream.readobject() should actually get a DER object and not ASN1. (To my understanding DER is a subtype of ASN1)
I then return the bytes.
This works half the time, but the other half I get this error:
java.io.IOException: DER length more than 4 bytes: XXX
My questions are:
- Why do I only get the error SOMETIMES? (I always give it 65 bytes of data)
- How do I fix it?
- Am I DER encoding the right way?