4

I had some problems where RSA keys created using the Security.Cryptography.RSAParameters were working only most of the time with RSACryptoServiceProvider.ImportParameters.

After a bunch of debugging it appears that the properties of that object want very specific byte buffer sizes. My ASN.1 parsing code has zero-byte-prefix elimination. In fact, some fields of the RSAParameters only work after zero-byte-prefix elimination and others don't work at all if zero-byte-prefix elimination has been done.

Every so often one of the parameters does have more leading zeros due to normal randomization and caused the resulting key to not work properly.

Is this something that is considered a bug?

poupou
  • 43,413
  • 6
  • 77
  • 174
Dan Maser
  • 41
  • 1

2 Answers2

2

Why are you messing around with those zero bytes? The correct DER encoding of a positive ASN.1 integer may involve a single leading zero byte. Simply put, if the high-order byte of the integer is 128 or larger then a leading zero byte must be prepended to the encoding. Without that zero byte you have the DER encoding of a negative integer.

President James K. Polk
  • 40,516
  • 21
  • 95
  • 125
  • 1
    (Thanks for your reply) Right, the ASN.1 integer can have a leading zero byte, but the point is that the RSAParameters object clearly doesn't wany ASN.1 formatted data, it wants byte arrays of a very specific size. So my code has to take the ASN.1 data from the DER encoded blob and extract the actual number bytes (ie, strip off the data type info from the ASN.1 format) and feed them to the RSAParameters as byte arrays. – Dan Maser Sep 29 '10 at 14:19
2

.NET requires the size of each RSA parameters to be of an exact size (wrt key pair size).

So sometimes you'll need to remove the leading 0x00 byte (e.g. if the data comes from ASN.1 which requires a leading 0 for positive numbers).

But other times you need to add an extra 0x00 byte because the bytes represent a (huge) number that might fit with fewer bytes (1 in reality). This occurs when parsing data from PEM (base64) encoded files where the leading 0 is generally removed.

Final answer: ensure you're provided the expected length (pad or remove padding).

poupou
  • 43,413
  • 6
  • 77
  • 174