C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » ASP.NET/Web Applications »

RSA Encryption in C#


Posted Date: 17 Nov 2004    Resource Type: Articles    Category: ASP.NET/Web Applications
Author: ANITA MARY JOSEPHMember Level: Gold    
Rating: 1 out of 5Points: 22



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.

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.






Responses

Author: Gary Le Sueur    09 Dec 2004Member Level: Bronze   Points : 0
Hi. Could you post an example of the XML file used for the key?

Also im not sure putting the XML key files in the root of the public webspace is such a good plan.........

Good code though, thanks


Author: Gary Le Sueur    09 Dec 2004Member Level: Bronze   Points : 0
Didn't read code properly, I see the AssignKey function creates the XML file :E




Author: Dan W Randolph    25 Mar 2005Member Level: Bronze   Points : 0
Good work. I found this a very well designed and easy-to-use class.


Author: Dan W Randolph    25 Mar 2005Member Level: Bronze   Points : 0
You might note that there is a length limit of the string to encrypt. MS documentation is unclear, but my test shows that a string type with length of 117 was the maximum I could get to encrypt. If you wanted to encrypt longer streams, you could break them into blocks.


Author: Gajo Csaba    17 Apr 2005Member Level: Bronze   Points : 0
This is a very good class for encrypting strings. I was looking for something like this for a long time. Congrats to the author!


Author: Raghu    26 Apr 2005Member Level: Bronze   Points : 0
your logic is working well in the place if the text, when i convert an file in to string and pass it, and encrypt.
After encrypting the file, if we restart the applicatio, trying to decrypt, where it fails.
Raghu


Author: gautam    14 Nov 2005Member Level: Bronze   Points : 0
Thanks Anita for the listing. Works just great.
Gautam Singaraju


Author: Shine Joseph    06 Mar 2008Member Level: Silver   Points : 0
I reject all Negatice Comments. This Code worked for me in the Fist compilation. I want to give direction to the prev comment's, that you just need to create files in the order and the keys will be generted as you click the "Add Key Button"

Thanks Ms. JOSEPH.


Author: Shine Joseph    11 Mar 2008Member Level: Silver   Points : 0
Hi,
When I try Encrypting a text in a local application, it throws an exception - "Object already exists."

And when I add this application to the IIs as a web application, It works fine with absolutly no errors. Can any one tell me wnhat is the reason...


For your referance, I added the Exception message below...

[System.Security.Cryptography.CryptographicException.ThrowCryptogaphicException(Int32 hr)\r\n at System.Security.Cryptography.Utils._CreateCSP(CspParameters param, Boolean randomKeyContainer, SafeProvHandle& hProv)\r\n at System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)\r\n at System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle)\r\n at System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair()]

The Error is thrown at line "rsa = new RSACryptoServiceProvider(cspParams); " in AssignParameter() method.



Author: sireesha    21 Oct 2008Member Level: Silver   Points : 1
Hi Shine Joseph

I am also getting the same problem...How did u overcome that problem? I would be greatful if u tell me the solution.



Siri


Author: sireesha    21 Oct 2008Member Level: Silver   Points : 1
Hi Shine Joseph

I am also getting the same problem...How did u overcome that problem? I would be greatful if u tell me the solution.



Siri


Author: Milton    24 Jun 2009Member Level: Bronze   Points : 0
Thanks 4 U r work.Keep posted when ever You can like This...
Milton J


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Adding checkox to a datagrid.
Previous Resource: Convert string to Date
Return to Discussion Resource Index
Post New Resource
Category: ASP.NET/Web Applications


Post resources and earn money!
 
Related Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use