How to store/retrieve RSA public/private key

Viewed 76722

I want to use RSA public key encryption. What is the best way to store or retrieve private and public keys? Is XML a good idea here?

How to get the keys?

RSAParameters privateKey = RSA.ExportParameters(true);
RSAParameters publicKey = RSA.ExportParameters(false);

Because RSAParameters have the following members: D, DP, DQ, Exponent, InverseQ, Modulus, P, Q

Which one is the key?

6 Answers

What I have done successfully is to store the keys as XML. There are two methods in RSACryptoServiceProvider: ToXmlString and FromXmlString. The ToXmlString will return an XML string containing either just the public key data or both the public and private key data depending on how you set its parameter. The FromXmlString method will populate the RSACryptoServiceProvider with the appropriate key data when provided an XML string containing either just the public key data or both the public and private key data.

Use a existing standard format, like PEM. Your crypto library should provide functions to load and save keys from files in PEM format.

Exponent and Modulus are the Public key. D and Modulus are the Private key. The other values allow faster computation for the holder of the Private key.

The public key is identified by Modulus and Exponent. The private key is identified by the other members.

I suppose answer from @Ian Boyd would not precisely, the format should be SSH2, instead of OpenSSH, as the RFC4716 defined for SSH2, OpenSSH format have is proprietary:

Note: That OpenSSH uses four dashes with a space (---- ) rather than five dashes and no space (-----).

Is XML a good idea here?

Normally Private keys are stored in HSM's/smart card. This provides a good security.

Related