开发者

Simple rsa encryption/decryption in .NET?

I'd like to generate pair of keys and just type something like:

Rsa.Decrypt(data, privateKey); 
Rsa.Encrypt(data, publicKey);

Is there any easy way to do this? I know there开发者_如何学JAVA is something like RsaCryptoServiceProvider but it needs XML to create proper object. I'd like to store private/public key as simple string (not xml) which i'll put in web.config in:

<appSettings>
    <add key="MyPublicKey" value"...."/>
    <add key="MyrivateKey" value"...."/>
</appSettings>

And later i'll encrypt web.config so everything will be safe (IIS will deal with it). Is it possible to do that in that way?


Create an RSACryptoServiceProvider object with your preferred keys size (512 / 1024 / 2048...):

int keySize = 1024;
m_ServiceProvider = new RSACryptoServiceProvider(keySize);

Or use the default size:

m_ServiceProvider = new RSACryptoServiceProvider();

Then use ExportParameters to get what you need at byte array, for example to get the Modulus part of the public key use:

byte[] publicModulus = m_ServiceProvider.ExportParameters(true).Modulus;

I've passed a true value in ExportParameters because you wanted access to the private key parameters.

and then you only need to convert the byte array to string:

string publicModulusStr = Convert.ToBase64String(modulus);

Later, when you want to read from the web.config and and recreate the RSACryptoServiceProvider object, create an RSAParameters object with the text you stored in the file and then pass the RSAParameters to the RSACryptoServiceProvider constructor.

And just a note: the web.config file you are saving should be kept very private since you store your private keys inside.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜