RSA Encryption in C#

来源:互联网 发布:淘宝美工素材打包下载 编辑:程序博客网 时间:2024/05/17 23:01
What is Encryption?

Encryption is the process of converting a string of characters into another such that the original characters cannot be deciphered upon examination. This process is performed with the use of another string of characters called the “KEY”.

Note: The strength of the encryption is determined by the size of the key used. So, The larger the key, the stronger the encryption!

There are generally two types of encryption techniques, Symmetric and Asymmetric.

Symmetrical Encryption

In symmetric encryption, a secret key is used to encrypt data and the very same key is used to decrypt it too
Examples: DES and RC2

Asymmetrical Encryption

Asymmetric encryption uses a related key-pair to encrypt and decrypt data.
One of the keys is the “public key” and the other is the “private key”.
The data encrypted with the public key can only be decrypted with the private key, and vice-versa.
RSA is one of the popular asymmetric algorithms and that’s what we’re going to deal with in this article.

To use the cryptographic services, we need to use the System.Security.Cryptography. namespace

Lets begin by creating the following files:
1. Cryptography.cs
2. publickey.xml
3. privatekey.xml
4. WebForm1.aspx

Code to Enable RSA Encryption/Decryption

Enter the following Code in your Cryptography.cs file.
Enter the following Code in your Cryptography.cs file.

public class Cryptography
{
 public static RSACryptoServiceProvider rsa;

 public static void AssignParameter()
 {
const int PROVIDER_RSA_FULL = 1;
const string CONTAINER_NAME = "SpiderContainer";
CspParameters cspParams;
cspParams = new CspParameters(PROVIDER_RSA_FULL);
cspParams.KeyContainerName = CONTAINER_NAME;
cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
cspParams.ProviderName = "Microsoft Strong Cryptographic Provider";
rsa = new RSACryptoServiceProvider(cspParams);
 }

 public static string EncryptData(string data2Encrypt)
 {
AssignParameter();
     StreamReader reader = new   StreamReader(@"C:/Inetpub/wwwroot/dotnetspiderencryption/publickey.xml");
string publicOnlyKeyXML = reader.ReadToEnd();
rsa.FromXmlString(publicOnlyKeyXML);
reader.Close();

//read plaintext, encrypt it to ciphertext

byte[] plainbytes =System.Text.Encoding.UTF8.GetBytes(data2Encrypt);
byte[] cipherbytes = rsa.Encrypt(plainbytes,false);
return Convert.ToBase64String(cipherbytes);
 }

 public static void AssignNewKey()
 {
AssignParameter();

//provide public and private RSA params
StreamWriter writer = new   StreamWriter(@"C:/Inetpub/wwwroot/dotnetspiderencryption/privatekey.xml");
string publicPrivateKeyXML = rsa.ToXmlString(true);
writer.Write(publicPrivateKeyXML);
writer.Close();

//provide public only RSA params
writer = new StreamWriter(@"C:/Inetpub/wwwroot/dotnetspiderencryption/publickey.xml");
string publicOnlyKeyXML = rsa.ToXmlString(false);
writer.Write(publicOnlyKeyXML);
writer.Close();

 }

 public static string DecryptData(string data2Decrypt)
 {
AssignParameter();

byte[] getpassword = Convert.FromBase64String(data2Decrypt);

StreamReader reader = new StreamReader(@"C:/Inetpub/wwwroot/dotnetspiderencryption/privatekey.xml");
string publicPrivateKeyXML = reader.ReadToEnd();
rsa.FromXmlString(publicPrivateKeyXML);
reader.Close();

//read ciphertext, decrypt it to plaintext
byte[] plain =rsa.Decrypt(getpassword,false);
return System.Text.Encoding.UTF8.GetString(plain);

}
}
When we create a new default constructor instance of the RSACryptoServiceProvider class, it automatically creates a new set of public / private key information, that’s ready to use. However, if we want to re-use previously created keys, we can do this by initializing the class with the populated CspParameters object, and that’s what we’ve done in the AssignParameter() method.

In the AssignNewKey() Method we are saving the key information from the cspParams object to the public.xml and private.xml files.
Note: this method should be called only once! Once we’ve got the key information into our private.xml and public.xml files we wont need to call this method again.

WebForm1.aspx

Create three TextBox(txt1, txt2, txt3) and three Button(AssignKey, Encrypt, Decrypt) Controls.
Add the Click Event Codes to the corresponding Controls:

AssignKey:  
Cryptography.AssignNewKey();

Encrypt:      
txt2.Text = Cryptography.EncryptData(txt1.Text);

Decrypt:      
Txt3.Text = Cryptography.DecryptData(txt2.Text);

Running the Program.

Click the Button ‘AssignKey’ first to store our key info to the xml files.
(Click only Once)…we can comment the AssignNewKey() method, coz we wont need to perform the action again.
Enter a value to txt1, press Encrypt to get the encrypted value to txt2, then press Decrypt to get the decrypted value to txt3.

So that’s about RSA Encryption, Do drop in your FeedBacks...Have a Nice Day :-)

Note: Though RSA Encryption provides increased security and convenience it Lacks speed when compared to other symmetric algorithms.