private int ReadLength()
{
int length = ReadByte();
if (length == 0x80)
{
throw new NotSupportedException("Indefinite-length encoding is not supported.");
}
if (length > 127)
{
var size = length & 0x7f;
// Note: The invalid long form "0xff" (see X.690 8.1.3.5c) will be caught here
if (size > 4)
throw new InvalidOperationException(string.Format("DER length is '{0}' and cannot be more than 4 bytes.", size));
length = 0;
for (var i = 0; i < size; i++)
{
int next = ReadByte();
length = (length << 8) + next;
}
if (length < 0)
throw new InvalidOperationException("Corrupted data - negative length found");
//if (length >= limit) // after all we must have read at least 1 byte
// throw new IOException("Corrupted stream - out of bounds length found");
}
return length;
}