1

I have a function that need RSA encryption/decryption. With provided .pem file, that contains pair key for RSA. By using Org.BouncyCastle as same as How to read a PEM RSA private key from .NET; or using the method in http://www.jensign.com/opensslkey/opensslkey.cs. What i received is "bad data" with parameter DQ has 63 byte (different from 64 byte). (the .pem file is said that been fine.) Is there any problem here?

Community
  • 1
  • 1
thongqn
  • 13
  • 2
  • What do you mean you received "bad data"? If you got an error message then copy and paste the full error message into your answer. – President James K. Polk Jul 11 '11 at 11:11
  • when i import parameter(D,Q,P,DQ...) into RSA, "bad data" occur. Cause of the diffirence in length of DQ. In ordinary, is should be 64 bytes of length of DQ, but in this case, it has 63 bytes. – thongqn Jul 13 '11 at 01:34

1 Answers1

2

All RSA parameters are simply (huge) numbers. Most of them will have identical sizes (for the same key pair length, e.g. 1024) but this is not always the case - and you need to cover this in your code.

Why ? because some numbers will be a bit smaller and will fit in less bits than others. In your case the number fits in 63 bytes, so it's base64 (PEM) encoded as such.

The solution is to pad the data you're reading, i.e. add a 0x00 byte before the 63 you're decoding. This will still be the same numbers (math wise) and it will pass all .NET validations for the RSA key parameters.

p.s. you can look at Mono source code to see how this is handled.

poupou
  • 43,413
  • 6
  • 77
  • 174