Skip Navigation Links.

RSA (ASP.NET)

RSA is an asymmetric encyption algorithm, which uses two keys, one to encrypt and the other to decrypt. It was created in 1977 by Ron Rivest, Adi Shamir, and Leonard Adleman, and is still one of the most widely used encryption methods. A typical application is in authenticating a sender, where the senders private key is used to encrypt a message, and then is decrypted by the receiver with the senders public key (which is known to anyone who wants it). It is also typically used for encrypting disks/files, such as for EFS.

Note: The RSA crypto function is restricted on an ASP.NET server. For a Windows version: [Click here]

Message:

The RSA algorithm generates the two key, as follows:

Public key
Private key
Ref of keys [Link]

Then the encrypted stream becomes:

 

and to test, the decrypted text is:

 

This works fine on my machine, but when it is ported to the Web server it gives:

System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.KeyContainerPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

and this is because the Web hostering providers block the loading of private keys as it could compromise the security of the Windows key store, thus most Web hosting providers turn it off so that it is not possible to comprise the system private keys.

The code is:

try
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

RSAParameters publickey = rsa.ExportParameters(false); // don't export private key
RSAParameters privatekey = rsa.ExportParameters(true); // export private key

this.tbPublicKey.Text = "e=" + ByteToString(publickey.Exponent) + ", n=" + ByteToString(publickey.Modulus);
this.tbPrivateKey.Text = "d=" + ByteToString(privatekey.D) + ", n=" + ByteToString(publickey.Modulus);


rsa.ImportParameters(publickey);
byte[] encryptedData = rsa.Encrypt(StringToByte(this.tbMessage.Text), true);
this.tbEncrypt.Text = ByteToString(encryptedData);

rsa.ImportParameters(privatekey);
byte[] decryptedData = rsa.Decrypt(encryptedData,true);

this.tbDecrypt.Text = ByteToString2(decryptedData);
}
catch (Exception ex)
{

this.tbEncrypt.Text = ex.Message.ToString();
}