Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 223
Simon Avatar asked Jul 06 '11 07:07

Simon


People also ask

How do I decrypt RSA encryption?

To decrypt a ciphertext C using an RSA public key we simply compute the plaintext M as: M = Cd mod N. Note that both RSA encryption and RSA decryption involve a modular exponentiation and so we would be well advised to use the Repeated Squares Algorithm if we want to make these processes reasonably efficient.

What is the encryption formula and decryption formula of RSA?

RSA Function Evaluation Encryption: F(m,e)=memodn=c, where m is the message, e is the public key and c is the cipher. Decryption: F(c,d)=cdmodn=m.

Is RSA easy to crack?

RSA is the standard cryptographic algorithm on the Internet. The method is publicly known but extremely hard to crack. It uses two keys for encryption. The public key is open and the client uses it to encrypt a random session key.


1 Answers

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.

like image 196
galbarm Avatar answered Oct 20 '22 06:10

galbarm