Click here to Skip to main content
15,881,092 members
Articles / Programming Languages / C#

RSA Private Key Encryption

Rate me:
Please Sign up or sign in to vote.
4.89/5 (72 votes)
4 Feb 2012CPOL3 min read 427.4K   45K   172   99
How to encrypt data using a private key in .NET.

RSA Introduction

The RSA (Rivest, Shamir, Adleman) encryption algorithm uses two Keys: Private and Public.

Scenario A

Suppose Alice wants to send a message to Bob (for his eyes only!). She can encrypt the message using the RSA algorithm with Bob's Public Key, which is not a secret (that's why they call it Public…). Once the message is encrypted, nobody can decrypt it, except the one holding the matching Private Key (that is Bob).

Scenario B

The reverse is also true: if Alice would encrypt the message using her own Private Key, Bob (and Eve, and everyone who can access this "encrypted" message) can decrypt it using Alice's Public Key. So, if everybody can decrypt it, what's the point in encrypting the message with a Private Key in the first place? Well, there is a point if Bob wants to make sure that the message has been written by Alice and not by someone else (Eve?).

.NET RSACryptoServiceProvider

The .NET Framework implements the RSA algorithm in the RSACryptoServiceProvider class. The instance of this class lets you create Key pairs, encrypt using a public key, decrypt using a private key (as in the first scenario), sign (sort of the second scenario, but not exactly), and verify the signature.

The Sign method accepts a message (as byte array) and creates a signature for this particular data. In the second scenario, Alice can write a message to Bob, and use this method to get a signature with her own private key. Then, she can send the message to Bob as is (unencrypted) with the signature. To verify the writer ID (Alice), Bob will use the Verify method with Alice's public key as: Verify(aliceMessage, aliceSignature), and he will get "true" if this is the original message written and signed by Alice, or "false" if even one bit has been changed since. This is one useful implementation of private key encryption, but sometimes it's just too complicated. You might want to send just a little message so the receiver can decrypt it and be sure it's from you, without the need to sign and send him both components.

RSA Private Key Encryption

Unfortunately, the RSACryptoServiceProvider class does not provide you this option, so I wrote my own implementation of the RSA algorithm using the basics of the RSACryptoServiceProvider in conjunction with Chew Keong TAN's class: BigInteger (http://www.codeproject.com/KB/cs/biginteger.aspx). At a low level, the RSA algorithm is about implementing mathematical equations on huge (huge) integers, so the BigInteger class is really essential. I couldn't have done it myself.

Using the RSAEncryption Class

The class has six main methods:

C#
void LoadPublicFromXml(string publicPath)
void LoadPrivateFromXml(string privatePath)
byte[] PrivateEncryption(byte[] data)
byte[] PublicEncryption(byte[] data)
byte[] PrivateDecryption(byte[] encryptedData)
byte[] PublicDecryption(byte[] encryptedData) 

I believe the method names are self explanatory. First, you have to create a private / public key pair, using the .NET RSACryptoServiceProvider class. To do that, you just create an instance of this class and then call the appropriate methods, like this:

C#
void LoadPublicFromXml(string publicPath)
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
File.WriteAllText(@"C:\privateKey.xml", rsa.ToXmlString(true));  // Private Key
File.WriteAllText(@"C:\publicKey.xml", rsa.ToXmlString(false));  // Public Key

// Then, you can load those files to RSAEncryption instance:
RSAEncryption myRsa = new RSAEncryption();
myRsa.LoadPrivateFromXml(@"C:\privateKey.xml");
myRsa.LoadPublicFromXml(@"C:\publicKey.xml");

// Once the keys are loaded (if you load a private key, there is no need to
// load the public one) you can start Encrypt / Decrypt data
// using Private / Public keys.
byte[] message = Encoding.UTF8.GetBytes("My secret message");
byte[] encryptMsg = myRsa.PrivateEncryption(message);

byte[] decryptMsg = myRsa.PublicDecryption(encryptMsg);
string originalMsg = Encoding.UTF8.GetString(decryptMsg);
// returns "My secret message"

WinForms Tester Application

To help you get started with the RSAEncryption and the RSACryptoServiceProvider classes, I wrote a WinForms tester application that uses those classes. All you need to do is just play with it a little and read the code-behind.

RSATesterMenu.png

RSATester.jpg

Update: New Version

The new implementation of the RSA Private Encryption has a few advantages:

  1. Bug fix: Added random padding to support 0 bytes prefix data.
  2. Uses the new .NET 4 "BigInteger" struct for math support.
  3. Extension methods implementation: the only class instance needed is RSACryptoServiceProvider.
  4. Better Exceptions and error handling.
  5. UnitTest project added.
  6. Generally, more elegant code (I hope..!).

Using the New Version

C#
string secret = "My secret message";
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(512);  // Key bits length
/*
* Skip the loading part for the RSACryptoServiceProvider will generate
* random Private / Public keys pair, that you can save later with
* rsa.ToXmlString(true);
* 
string key = "private or public key as xml string";
rsa.FromXmlString(key);
*/
// Convert the string to byte array
byte[] secretData = Encoding.UTF8.GetBytes(secret);

// Encrypt it using the private key:
byte[] encrypted = rsa.PrivareEncryption(secretData);

// Decrypt it using the public key
byte[] decrypted = rsa.PublicDecryption(encrypted);
string decString = Encoding.UTF8.GetString(decrypted);  // And back to string
Assert.AreEqual("My secret message", decString);

History

  • 4th August, 2009: Initial post.
  • 5th August, 2009: Improved code to check the state of the uploaded keys before trying to make the encryption / decryption.
  • 1st February, 2012: Improved and fixed new version.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer WonderNet
Israel Israel
I speak three languages: C#, Hebrew and English...
Programming is my work, my hobby and my second love.
I work for an Israeli company named "WonderNet" that deal with digital signature solutions,
combined with Biometrics hand written signature (on a Wacom tablet).
We develop web application as well as client desktop ones,
using the .NET framwork: ASP.NET, C#, SQL-Server and more.
Cryptography is my "thing" since I lay my hand on Simon Singh work of art "The Code Book".

Comments and Discussions

 
QuestionGreat - thanks! (My vote of 5) Pin
Andreas Daxer13-Mar-24 2:03
Andreas Daxer13-Mar-24 2:03 
QuestionGood point about B Pin
peterkmx15-Aug-22 9:02
professionalpeterkmx15-Aug-22 9:02 
PraiseThanks a lot! You saved life! Pin
ledangdung13-Nov-21 17:14
ledangdung13-Nov-21 17:14 
QuestionUsing a private base64 encoded text as private key Pin
ssaguiar24-Feb-21 5:28
ssaguiar24-Feb-21 5:28 
QuestionPadding problem Pin
Jon Fernandez2-Dec-20 11:49
Jon Fernandez2-Dec-20 11:49 
QuestionLike your style! Your simple!!! Pin
Redlightpacket16-Sep-19 19:57
Redlightpacket16-Sep-19 19:57 
QuestionExtra Byte?? Pin
iqueue29-Apr-19 17:56
iqueue29-Apr-19 17:56 
QuestionHaving problems with decrypting a signature created by OpenSSL Pin
Member 876784112-Apr-19 7:00
Member 876784112-Apr-19 7:00 
GeneralMy vote of 5 Pin
BradleyInKona23-Mar-19 9:57
BradleyInKona23-Mar-19 9:57 
GeneralMy vote of 5 Pin
Member 136508367-Feb-19 0:18
Member 136508367-Feb-19 0:18 
Questionpublic encryption / private decryption Pin
Member 1413119828-Jan-19 22:33
Member 1413119828-Jan-19 22:33 
PraiseReviewed Pin
Divyans Mahansaria14-Oct-18 3:55
professionalDivyans Mahansaria14-Oct-18 3:55 
Questionhow encrypt this file Pin
Member 1370002127-Feb-18 10:35
Member 1370002127-Feb-18 10:35 
AnswerRe: how encrypt this file Pin
OriginalGriff27-Feb-18 10:39
mveOriginalGriff27-Feb-18 10:39 
AnswerRe: how encrypt this file Pin
Member 1370002128-Feb-18 20:47
Member 1370002128-Feb-18 20:47 
QuestionWould you please upload or provide System.Numerics.dll for this project? Pin
Member 135065146-Nov-17 9:28
Member 135065146-Nov-17 9:28 
Generaltry with another private key Pin
AZHAR SAYYAD12-Jun-17 21:53
AZHAR SAYYAD12-Jun-17 21:53 
QuestionStarting the application Pin
Member 1232803419-Apr-17 2:49
Member 1232803419-Apr-17 2:49 
AnswerRe: Starting the application Pin
Dudi Bedner19-Apr-17 6:04
Dudi Bedner19-Apr-17 6:04 
QuestionIt helped me a lot Pin
ashokrathore150320-Feb-17 18:33
ashokrathore150320-Feb-17 18:33 
QuestionAOEP Decode error Pin
Sergio Rius25-Feb-16 1:57
Sergio Rius25-Feb-16 1:57 
AnswerRe: AOEP Decode error Pin
Dudi Bedner30-Mar-16 5:09
Dudi Bedner30-Mar-16 5:09 
GeneralMy vote of 5 Pin
Franc Morales18-Jan-16 16:16
Franc Morales18-Jan-16 16:16 
PraiseRe: My vote of 5 Pin
Dudi Bedner30-Mar-16 5:04
Dudi Bedner30-Mar-16 5:04 
Thanks!
SuggestionWhat about large message Lets say 100 MB of data. Pin
saqibsabir2-Jan-15 5:29
saqibsabir2-Jan-15 5:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.