user1741276
user1741276

Reputation: 51

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,

Upvotes: 5

Views: 3544

Answers (3)

Paul Thorpe
Paul Thorpe

Reputation: 2060

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.

Upvotes: 2

Lev Walkin
Lev Walkin

Reputation: 111

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.

Upvotes: 0

SquareRootOfTwentyThree
SquareRootOfTwentyThree

Reputation: 7776

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.

Upvotes: 0

Related Questions