在.NET中简单的RSA加密/解密? [英] Simple rsa encryption/decryption in .NET?

查看:168
本文介绍了在.NET中简单的RSA加密/解密?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一对密钥,并只需键入是这样的:

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

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



有没有简单的方法来做到这一点?我知道有类似的RSACryptoServiceProvider但它需要XML创建正确的对象。我想存储私有/公共密钥简单的字符串(不是XML),我会把在web.config中的:

Is there any easy way to do this? I know there 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>

和我稍后会进行加密的web.config所以一切都将是安全的(IIS会处理它) 。是否有可能做到这一点的呀?

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?

推荐答案

用你喜欢的按键尺寸(512 /2048分之1024创建的RSACryptoServiceProvider对象...):

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

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

或使用默认的尺寸:

m_ServiceProvider = new RSACryptoServiceProvider();



然后使用ExportParameters得到你需要的字节数组的东西,比如获得的模量的一部分公钥用途:

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;



我在ExportParameters因为你想私钥参数访问通过了真正的价值。

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);



后来,当你想从web.config中读取并重新创建的RSACryptoServiceProvider对象,创建RSAParameters与你存储在文件中,然后通过RSAParameters到的RSACryptoServiceProvider构造文本对象

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.

和刚一说明:您要保存应该是web.config文件一直非常私人的,因为你里面存储的私钥。

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

这篇关于在.NET中简单的RSA加密/解密?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆