Is the length of a DER-encoded RSAPublicKey (PKCS #1) for a 1024-bit RSA key pair consistent?

梦想与她 提交于 2019-12-12 04:45:45

问题


I've created multiple 1024-bit DER-encoded RSAPublicKeys (PKCS #1) with the openssl command:

openssl genrsa 1024 | openssl rsa -outform DER -RSAPublicKey_out -out pubkey.der

So far, every public key file created like this has been exactly 140 bytes. Are 1024-bit RSA public keys encoded in this format always 140 bytes, or can this size vary?

I've learned that the size of a DER encoded private key can vary.


回答1:


It should always be 140 bytes for a 1024-bit key using an exponent value of F4 (0x010001).

The encoding of the public key is

SEQUENCE (RSAPublicKey)
30 xa [ya [za ...]]
   INTEGER (n)
   02 xb [yb [zb ...]] [pb] ...
   INTEGER (e)
   02 xc [yc [zc ...]] [pc] ...

Where pb and pc are optional padding bytes (to prevent the integers from being negative), and the xa-xc (and y/za-c) values are BER lengths.

If e is 0x010001 then it encodes as 02 03 01 00 01, always 5 bytes.

The keysize of an RSA key is determined by the length of the bit string starting with the first set bit. So for a 1024-bit key the value will be between 2^1023 and 2^1024, and that it will look like

0b1xxx_xxxx {1016 other "don't care" bits}

Since the high bit is set, the number would be negative without padding, so the 1024-bit number gets encoded to 128 value bytes and one leading byte of "the sign bit isn't set", or 129 bytes.

So now we know the integer's full encoded length, 129. That's 0x81 in hex, which is bigger than 0x79 (the biggest "compact" BER length), so the length gets written in long form: 0x81 (the length is expressed in the next 1 byte(s)) 0x81.

02 81 81 00 [128 more bytes representing n]

So e encoded to 5 bytes, and n encodes to 132 (128 + 1 + 2 + 1), which is 137.

137 in hex is 0x89, making the sequence length be 0x81 0x89. 137 bytes of content + 2 bytes of length + 1 byte of tag => 140 bytes.

30 81 89
   02 81 81 00 [128 more bytes of n]
   02 03 01 00 01

This computation assumes that no one is being bad with their definition of the key size. A loose interpretation (which, per http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Br1.pdf is wrong) would put the value of n between 2^1016 and 2^1024 (aka "it required 128 bytes, who cares which bit is the highest one set?"). In that case the padding byte could disappear from n and the length would drop to 139.



来源:https://stackoverflow.com/questions/47085654/is-the-length-of-a-der-encoded-rsapublickey-pkcs-1-for-a-1024-bit-rsa-key-pai

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!