问题
Why is the modulus padded with leading zeros? I was reading PKCS#1 and PKCS#8 but didn't find anything about it. In c# the leading zeros must be removed, does anybody know why?
At http://etherhack.co.uk/asymmetric/docs/rsa_key_breakdown.html, you can see that the modulus and exponent have leading zeros. The question is why they have it, I haven't found an explanation anywhere yet.
回答1:
The private key values are encoded as ASN.1 INTEGERs, which are signed values in two's complement format. The leading zero byte is necessary when the MSB of the (unsigned) RSA key value is set. Having the MSB set without a leading zero byte would mean a negative value.
The ASN.1 specs are free and are linked from Wikipedia. The relevant section here is in X.690, "8.3 Encoding of an integer value".
I'll provide an example here in case the linked page goes away.
If you have openssl, you can generate test keys with:
openssl genrsa -out test.pem 512
openssl rsa -in test.pem -out test.der -outform der
Here's sample data from test.der:
30 82 01 3b
ASN.1 SEQUENCE, length 0x13b, contents follow
02 01 00
version: ASN.1 INTEGER, stored length 1, value 0
02 41 00 c0 8e ...
(65 data bytes)
modulus: ASN.1 INTEGER, stored length 65, value 0xc08e... (leading zero byte required because modulus is > 2^511)
02 03 01 00 01
public exponent: 0x10001 (leading zero byte not required because exponent is < 2^23)
02 41 00 b5 87 ...
(65 data bytes)
private exponent: 0xb587...
02 21 00 e7 18 ...
(33 data bytes)
prime1: 0xe718...
02 21 00 d5 43 ...
(33 data bytes)
prime2: 0xd543...
02 20 75 67 a1 ...
(32 data bytes)
exponent1: 0x7567... (leading zero byte not required because exponent is < 2^255)
02 20 0a f6 3f ...
(32 data bytes)
exponent2: 0x0af6...
02 21 00 c7 13 ...
(33 data bytes)
coefficient: 0xc713...
来源:https://stackoverflow.com/questions/5974633/asn-1-der-formatted-private-key