dotnetspider.com


 


TutorialsForumResourcesReviewsJobsInterviewVideosCommunitiesProjectsTraining

Subscribe to Subscribers


Online MembersAnu George
Shesh Kumar Mishra
saranya
Anil Kumar Pandey
Suneetha
amol
sravan
chaminda
sandy
Prasad kulkarni
More...




Resources » Articles » ASP.NET/Web Applications


RSA Encryption in C#


Posted Date:     Category: ASP.NET/Web Applications    Rating: 1 out of 5
Author: Member Level: Gold    Points: 22


The article gives an example of The RSA Encryption. RSA Encryption is said to provide increased security!


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.


Did you like this resource? Share it with your friends and show your love!





Responses to "RSA Encryption in C#"
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



Author: Geoffrey Anderson    26 Feb 2010Member Level: Bronze   Points : 1
You say "data encrypted with the public key can only be decrypted with the private key, and vice-versa", however when the keys in your code are reversed (ie, encrypt with private key and decrypt with public), a Bad Key exception is thrown when decryption is attempted.


Author: Ahmad Nauman    10 May 2010Member Level: Bronze   Points : 2
Those who do not know about this before, can get useful information from this post, this one seems to me as another type of post .... and I want to say that way, as you tried to explain some posts here it seems to me the different ... There are, of course, in various positions in here, but I didn't find any post in connection with projects like cisa exam questions... If someone has information about it, tell me! Well, all the updates related to this position? if so, tell me! I actually came here while surfing online for information related to the project ccnt and find this post different one ... Is there anyone having information on the exam 70-270 , ccie lab?, If so, what to do, tell me! ... any updates, and if so, what tell me!







Author: Tom Jackson    21 Jul 2010Member Level: Bronze   Points : 2
Great article and these routines saved me a lot of heartache and time! There were some issues I had (and anyone that uses these will have to, as well) to overcome, though:
1) public static RSACryptoServiceProvider rsa; sharing does not work - you have to have it at the top of each individual function like this: RSACryptoServiceProvider rsa = new RSACryptoServiceProvider rsa(1024); (or whatever key length you want)
2) You have to call AssignNewKey() before doing anything, and then only once. I solved this with an "init" argument in my console app, where this routine is triggered.
3) You must check for the existance of the XML files before you can create new ones, and FileStreams are needed where there are only StreamWriters in this code, and they must be referenced in the StreamWriters, like this:

public static void AssignNewKey()
{
AssignParameter();
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024);

if (File.Exists("privatekey.xml") == true)
File.Delete("privatekey.xml");
if (File.Exists("publickey.xml") == true)
File.Delete("publickey.xml");
//provide public and private RSA params
FileStream fs1 = new FileStream("privatekey.xml", FileMode.CreateNew, FileAccess.ReadWrite);
StreamWriter sw1 = new StreamWriter(fs1);
string publicPrivateKeyXML = rsa.ToXmlString(true);
sw1.Write(publicPrivateKeyXML);
sw1.Close(); //provide public only RSA params
fs1.Close();

FileStream fs2 = new FileStream("publickey.xml", FileMode.CreateNew, FileAccess.ReadWrite);
StreamWriter sw2 = new StreamWriter(fs2);
string publicOnlyKeyXML = rsa.ToXmlString(false);
sw2.Write(publicOnlyKeyXML);
sw2.Close();
fs2.Close();
}
4) You have to have write access where you are creating the XML files.


Luckily these were all the bugs I found. But overall, great job!

Thanks!

-Tom



Feedbacks      

Post Comment:




  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Next Resource: Adding checkox to a datagrid.
    Previous Resource: Convert string to Date
    Return to Resources
    Post New Resource
    Category: ASP.NET/Web Applications


    Post resources and earn money!
     
    More Resources
    Popular Tags   Tag posting guidelines   Search Tags  
    (No tags found.)

    My Profile

    Active Members
    TodayLast 7 Daysmore...


    Awards & Gifts


    Email subscription
  • .NET Jobs
  • .NET Articles
  • .NET Forums
  • Articles Rss Feeds
    Forum Rss Feeds



    About Us    Trademark Disclaimer    Contact Us    Copyright    Privacy Policy    Terms Of Use    Revenue Sharing sites   Advertise   Talk to Tony John
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India
    2005 - 2012 All Rights Reserved.
    .NET and other trademarks mentioned in this site belong to Microsoft and other respective trademark owners.
    Articles, tutorials and all other content offered here is for educational purpose only.
    We are not associated with Microsoft or its partners.