简体   繁体   English

.NET 中的简单 rsa 加密/解密?

[英]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 is something like RsaCryptoServiceProvider but it needs XML to create proper object.我知道有类似 RsaCryptoServiceProvider 的东西,但它需要 XML 来创建正确的 object。 I'd like to store private/public key as simple string (not xml) which i'll put in web.config in:我想将私钥/公钥存储为简单的字符串(不是 xml),我将把它放在 web.config 中:

<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).稍后我将加密 web.config 以便一切安全(IIS 将处理它)。 Is it possible to do that in that way?有可能这样做吗?

Create an RSACryptoServiceProvider object with your preferred keys size (512 / 1024 / 2048...):使用您的首选密钥大小(512 / 1024 / 2048...)创建一个 RSACryptoServiceProvider object:

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:然后使用 ExportParameters 在字节数组中获取您需要的内容,例如获取公钥使用的 Modulus 部分:

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

I've passed a true value in ExportParameters because you wanted access to the private key parameters.我在 ExportParameters 中传递了一个真值,因为您想要访问私钥参数。

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.稍后,当您想从 web.config 中读取并重新创建 RSACryptoServiceProvider object 时,创建一个 RSAParameters object 并将您存储在 RSA 文件中的文本传递给 RSAServiceProvider.oCryptoServiceProvider

And just a note: the web.config file you are saving should be kept very private since you store your private keys inside.请注意:您保存的 web.config 文件应该非常私密,因为您将私钥存储在其中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM