Click here to Skip to main content
Licence 
First Posted 24 May 2007
Views 49,847
Bookmarked 33 times

Data Encryption/Decryption using RSACryptoServiceProvider and X509Certificate2

By | 24 May 2007 | Article
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

About the Author

ranajitbiswal

Web Developer

India India

Member

Warking as a Senior Software Designer in Tech Mahindra Ltd.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionWhy search for matching cert when you grab first element? PinmemberScott McCain11:57 15 Apr '10  
AnswerRe: Why search for matching cert when you grab first element? Pinmemberranajitbiswal4:28 26 Jul '10  
AnswerRe: Why search for matching cert when you grab first element? PinmemberTrashkid20004:36 3 Sep '11  
Generalerror occur while decoding OAEP Padding PinmemberMeetu Choudhary0:25 5 Jun '09  
AnswerRe: error occur while decoding OAEP Padding Pinmemberpeteyb13139:35 3 May '11  
GeneralBad Key Pinmemberlewis12271:47 26 Mar '08  
GeneralRe: Bad Key Pinmemberm_bansal44412:17 21 Aug '08  
GeneralRe: Bad Key PinmemberSergey Sotnikov19:44 12 Nov '08  
GeneralRe: Bad Key Pinmembervanditd20:51 24 Nov '11  
GeneralSign File Pinmembershah_pranav1@yahoo.co.in0:46 22 Feb '08  
GeneralError in Decryption PinmemberMember 64724018:54 5 Feb '08  
GeneralFormatting PinmemberJeffrey Walton7:52 24 May '07  

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

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 24 May 2007
Article Copyright 2007 by ranajitbiswal
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid