简体   繁体   中英

Oddity when encoding large integers using asn.1

I have found numerous references to the encoding requirements of Integers in ASN.1 and that Integers are inherently signed objects

TLV 02 02 0123 for exmaple.

However, I have a 256 bit integer (within a certificate) encoded 30 82 01 09 02 82 01 00 d1 a5 xx xx xx… 02 03 010001

30 start 82 2 byte length 0109 265 bytes

02 Integer 82 2 byte length 0100 256 bytes d1 a5 xxxx

The d1 is the troubling part because the leading bit is 1, meaning this 256 bit number is signed when in fact it is an unsigned number, a public rsa key infact. Does the signed constraint apply to Integers > 64 bits?

Thanks,

BER/DER uses 2s-complement representation for encoding integer values. This means the the first bit (not byte) determines whether a number is positive or negative. This means that sometimes an extra leading zero byte needs to be added to prevent the first bit from causing the integer to be interpreted as a negative number. Note that it is invalid BER/DER to have the first 9 bits all zero.

Yes, you are right. For any non negative DER/BER-encoded INTEGER - no matter its length - the MSB of the first payload byte is 0.

The program that generated such key is incorrect.

The "signed constraint" (actually, a rule) totally applies to any size integers. However, depending on a domain you might find all sorts of oddities in how domain objects are encoded. This is something that has to be learned and accounted for the hard way, unfortunately.

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