Click here to Skip to main content
15,914,642 members
Articles / Database Development / SQL Server
Article

Data Encryption/Decryption using RSACryptoServiceProvider and X509Certificate2

Rate me:
Please Sign up or sign in to vote.
1.17/5 (11 votes)
24 May 20072 min read 110.7K   38   13
Data Encryption/Decryption using RSACryptoServiceProvider and X509Certificate2

Introduction

Data Encryption/Decryption using RSACryptoServiceProvider and X509Certificate2

Background

Before you write Encryption/Decryption, you must ensure your have genate valid certificate with having private key option. and can be achieved by following command.

makecert -r -pe -n "CN=MyTestServer" -b 01/01/2000 -e 01/01/2036 -eku 1.3.6.1.5.5.7.3.1 -ss my -sr CurrentUser -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12

Using the code

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Security.Cryptography.X509Certificates;
using System.Runtime.InteropServices;

string DigitalCertificateName = "";
/// <summary>
/// Constructor
/// Author : Ranajit Biswal
/// Date : 24th May 2007
/// Pupose : Used to Encrypt and Decrypt string using Digital signature which having Private Key.
/// Requirement : WSE 2.0 and .Net Framework 2.0
/// </summary>

//Read digital certificate from Current User store.
public string GetEncryptedText(string PlainStringToEncrypt)
{
X509Store store = new X509Store(StoreName.My);
X509Certificate2 x509_2 = null;
store.Open(OpenFlags.ReadWrite);
if (DigitalCertificateName.Length > 0)
{
foreach (X509Certificate2 cert in store.Certificates)
{
if (cert.SubjectName.Name.Contains(DigitalCertificateName))
{
x509_2 = cert;
break;
}
}

if (x509_2 == null)
throw new Exception("No Certificate could be found in name " + DigitalCertificateName);
}
else
{
x509_2 = store.Certificates[0];
}

try
{
string PlainString = PlainStringToEncrypt.Trim();
byte[] cipherbytes = ASCIIEncoding.ASCII.GetBytes(PlainString);
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509_2.PublicKey.Key;
byte[] cipher = rsa.Encrypt(cipherbytes, false);
return Convert.ToBase64String(cipher);
}
catch (Exception e)
{
//Hadle exception
throw e;
}

}//Method ends here

/// <summary>
/// To Decrypt clear text using RSACryptoServer Provider and Digital Certificate having Private Key.
/// </summary>
/// <param name="EncryptedStringToDecrypt"></param>
/// <returns></returns>
public string GetDecryptedText(string EncryptedStringToDecrypt)
{
X509Store store = new X509Store(StoreName.My);
X509Certificate2 x509_2 = null;
store.Open(OpenFlags.ReadWrite);
if (DigitalCertificateName.Length > 0)
{
foreach (X509Certificate2 cert in store.Certificates)
{
if (cert.SubjectName.Name.Contains(DigitalCertificateName))
{
x509_2 = cert;
break;
}
}
if (x509_2 == null)
throw new Exception("No Certificate could be found in name " + DigitalCertificateName);
}
else
{
x509_2 = store.Certificates[0];
}

try
{
byte[] cipherbytes = Convert.FromBase64String(EncryptedStringToDecrypt);
if (x509_2.HasPrivateKey)
{
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509_2.PrivateKey;
byte[] plainbytes = rsa.Decrypt(cipherbytes, false);
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
return enc.GetString(plainbytes);
}
else
{
throw new Exception("Certificate used for has no private key.");
}
}
catch (Exception e)
{
//Hadle exception
throw e;
}
}//method ends here

History

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Architect Tech Mahindra Ltd.
India India
Warking as a Solution Architect in Tech Mahindra Ltd.

Comments and Discussions

 
QuestionWhy search for matching cert when you grab first element? Pin
Scott McCain15-Apr-10 11:57
Scott McCain15-Apr-10 11:57 
AnswerRe: Why search for matching cert when you grab first element? Pin
ranajitbiswal26-Jul-10 4:28
ranajitbiswal26-Jul-10 4:28 
AnswerRe: Why search for matching cert when you grab first element? Pin
Trashkid20003-Sep-11 4:36
Trashkid20003-Sep-11 4:36 
Generalerror occur while decoding OAEP Padding Pin
Meetu Choudhary5-Jun-09 0:25
Meetu Choudhary5-Jun-09 0:25 
AnswerRe: error occur while decoding OAEP Padding Pin
peteyb13133-May-11 9:35
peteyb13133-May-11 9:35 
GeneralRe: error occur while decoding OAEP Padding Pin
zenox31-May-12 6:28
zenox31-May-12 6:28 
GeneralBad Key Pin
lewis122726-Mar-08 1:47
lewis122726-Mar-08 1:47 
GeneralRe: Bad Key Pin
cooldude00721-Aug-08 12:17
cooldude00721-Aug-08 12:17 
Ranajit,
Your article is great, it works great in WCF services as long as I have the my WCF client as well as my WCF Service on the same machine, but when I move the client to a different machine (and installed the certificate on client machine) but it doesn't seems to get thru. It throws me Bad Key exception. From my findings it looks like there is a setting in the certificate which says "Enhanced Key Usage" and value is Server Authentication(1.3.6.....), is this something I need to change to make it work across machines? If yes, please let me know how to do that.

Any help will be highly appreciated. I'm kinda stuck on this and need to get this working to be able to release it Frown | :(



Mayank
GeneralRe: Bad Key Pin
Sergey Sotnikov12-Nov-08 19:44
Sergey Sotnikov12-Nov-08 19:44 
GeneralRe: Bad Key Pin
vanditd24-Nov-11 20:51
vanditd24-Nov-11 20:51 
GeneralSign File Pin
shah_pranav122-Feb-08 0:46
shah_pranav122-Feb-08 0:46 
GeneralError in Decryption Pin
Member 6472405-Feb-08 18:54
Member 6472405-Feb-08 18:54 
GeneralFormatting Pin
Jeffrey Walton24-May-07 7:52
Jeffrey Walton24-May-07 7:52 

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.