Encrypt and Decrypt

Topics: Cryptography Application Block, Security Application Block
May 13, 2009 at 6:30 AM
Edited May 13, 2009 at 6:33 AM

Hello Experts,

I am developing a web application in asp.net 3.5 framework with C# and in that application i have a rich textbox or multi line text box which contains data of n length and i want to encrypt and decrypt the data using the digital signatures

please consider that the user using the web application is already having the digital signatures from a Gov. recognized body and my application will not create any Digital Signature it will only use the .pfx file or the installed signature I am able to open the certificate store and it is displaying all the certificates installed on the computer.

now what i need is i want to encrypt the data using the digital signature's public key and decrypt it using the private key of the same digital signature. I may save the public key in the DB for encryption but to decrypt the data we need the digital signature.

I am Trying this code:

protected void Button2_Click(System.Object sender, System.EventArgs e)


Label2.Text = "";

//first set ICryptoTransform for encryption later

ICryptoTransform encryptor;

byte[] toEncrypt;



//CreateEncryptor for encryption later

encryptor = Rin.CreateEncryptor(Rin.Key, Rin.IV);

//use main memory for I/O.

MemoryStream msEncrypt = new MemoryStream();

//get CryptoStream for encrypted data

CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);

//Convert the data to a byte array.

toEncrypt = Encoding.ASCII.GetBytes(this.txtusername.Text);

//Write all data to the crypto stream and flush it.

csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);


//Get encrypted array of bytes.

EncData = msEncrypt.ToArray();



IntPtr hCertStore = IntPtr.Zero;

IntPtr p2 = IntPtr.Zero;


IntPtr pCertContext = IntPtr.Zero;

IntPtr k = IntPtr.Zero;

IntPtr j = IntPtr.Zero;

IntPtr h = IntPtr.Zero;

string certcnt;

string kk = "MY";

string pszNameString;

int provinfosize = 0;

int RSAkeytype;

StringBuilder uu = new StringBuilder(128);

CspParameters csp = new CspParameters();

j =CertFun.CertOpenSystemStore(IntPtr.Zero, kk);

hCertStore = j;


k = CertFun.CryptUIDlgSelectCertificateFromStore(hCertStore, IntPtr.Zero, "Personal Store", "Please select a PKC12 (.pfx) Certificate and press ok", cf.CRYPTUI_SELECT_LOCATION_COLUMN, 0, IntPtr.Zero);

pCertContext = k;



System.Security.Cryptography.X509Certificates.X509Certificate2 x = new X509Certificate2(k);

if (x.HasPrivateKey)


Response.Write("PrivateKey "+x.PrivateKey.ToXmlString(false) + "<br>");

//Response.Write("GetPublicKey()"+x.GetPublicKey() + "<br>");

Response.Write("GetPublicKeyString()"+x.GetPublicKeyString() + "<br>");

Response.Write("GetSerialNumberString()"+x.GetSerialNumberString() + "<br>");

//Response.Write("GetSerialNumber()"+x.GetSerialNumber() + "<br>");

//Response.Write("PublicKey"+x.PublicKey + "<br>");

Response.Write("SerialNumber"+x.SerialNumber + "<br>");

Response.Write("Thumbprint"+x.Thumbprint + "<br>");

Response.Write("GetRawCertDataString()" + x.GetRawCertDataString() + "<br>");



CAPICOM.CertificateClass c = new CertificateClass();


Response.Write("CAPICOM <br>");

//c.PrivateKey.Open(c.PrivateKey.ContainerName, c.PrivateKey.ProviderName, c.PrivateKey.ProviderType, c.PrivateKey.KeySpec, CAPICOM_STORE_LOCATION.CAPICOM_CURRENT_USER_STORE | CAPICOM_STORE_LOCATION.CAPICOM_LOCAL_MACHINE_STORE, true);

Response.Write("c.PrivateKey.IsExportable" + c.PrivateKey.IsExportable()+"<br>");

Response.Write("c.SerialNumber " + c.SerialNumber + "<br>");

Response.Write("c.ICertificate_Thumbprint " + c.ICertificate_Thumbprint + "<br>");




if (pCertContext.Equals(IntPtr.Zero))


Debug.Write("You didn't select a certificate");



//chk cert is PKCS12

if (!CertFun.CertGetCertificateContextProperty(pCertContext,cf.CERT_KEY_PROV_INFO_PROP_ID, IntPtr.Zero,ref provinfosize))


if (!(pCertContext.Equals(IntPtr.Zero)))




Debug.Write ("Selected certificate is not PKCS12. Please select a PKCS12 certificate");





// yes pkcs12


if ((CertFun.CertGetNameString(pCertContext, cf.CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, IntPtr.Zero, uu, 128)))



// MsgBox("Selected Certificate Name is " & uu.ToString)



// MsgBox("CertGetName failed")


X509Certificate cert = new X509Certificate(pCertContext);

//get PKC12 cert selected by user

byte[] encodedpubkey = cert.GetPublicKey();

int blobbytes = 0;

bool verbose = false;

if ((CertFun.CryptDecodeObject(CertFun.ENCODING_TYPE, cf.RSA_CSP_PUBLICKEYBLOB, encodedpubkey, encodedpubkey.Length, 0, null,ref blobbytes)))


byte[] publickeyblob = new byte[blobbytes];

if ((CertFun.CryptDecodeObject(CertFun.ENCODING_TYPE, cf.RSA_CSP_PUBLICKEYBLOB, encodedpubkey, encodedpubkey.Length, 0, publickeyblob, ref blobbytes)))


cf.pubblob = publickeyblob;




Console.WriteLine("Couldn't decode publickeyblob from certificate publickey");




int headerslength = Marshal.SizeOf(pkheaders);

IntPtr buffer = Marshal.AllocHGlobal(headerslength);

Marshal.Copy(cf.pubblob, 0, buffer, headerslength);

//pkheaders = (PUBKEYBLOBHEADERS) Marshal.PtrToStructure( buffer, typeof(PUBKEYBLOBHEADERS) );

pkheaders = (CertFun.PUBKEYBLOBHEADERS)Marshal.PtrToStructure(buffer, typeof(CertFun.PUBKEYBLOBHEADERS));


byte[] modulus;

byte[] certkeymodulus;

byte[] certkeyexponent;

int certkeysize;

certkeysize = pkheaders.bitlen;

////----- Get public exponent -------------

byte[] exponent = BitConverter.GetBytes(pkheaders.pubexp);

// //little-endian ordered


certkeyexponent = exponent;

////----- Get modulus -------------

int modulusbytes = (int)pkheaders.bitlen / 8;

//modulus = new byte[modulusbytes - 1] { };

modulus = new byte[2500] ;

// Dim datatoEnc() As Byte = ASCIIEncoding.ASCII.GetBytes(TextBox4.Text)

Array.Copy(cf.pubblob, headerslength, modulus, 0, modulusbytes);


// //convert from little to big-endian ordering.

certkeymodulus = modulus;

// Dim Tempenckey() As Byte

RSAParameters RSAKeyInfo = new RSAParameters();

RSAKeyInfo.Modulus =(byte[]) modulus.Clone(); // md

RSAKeyInfo.Exponent = (byte[])exponent.Clone(); // exp


RSACryptoServiceProvider oRSA = new RSACryptoServiceProvider();


//Now secret key is encrypted with cert Pub key

//send this file to sender

//cf.EncKey = oRSA.Encrypt(Rin.Key, false);

/*Changed the above line to*/

cf.EncKey = oRSA.Encrypt(Rin.Key, false );

cf.EncIv = oRSA.Encrypt(Rin.IV, false);

//comvert to base64 string

string wstrkey = Convert.ToBase64String(cf.EncKey);

string wstriv = Convert.ToBase64String(cf.EncIv);

if (!(pCertContext.Equals(IntPtr.Zero)))




if (!(hCertStore.Equals(IntPtr.Zero)))


CertFun.CertCloseStore(hCertStore, 0);


// write to fresh file

FileStream fs = new FileStream(SKey, FileMode.Create);

// Create the writer for data.

BinaryWriter w = new BinaryWriter(fs);

// Write data to Test.data.

int i;

for (i = 0; i <= cf.EncKey.GetUpperBound(0); i++)






// write to fresh file

FileStream fs1 = new FileStream(SIV, FileMode.Create);

// Create the writer for data.

BinaryWriter w1 = new BinaryWriter(fs1);

// Write data to Test.data.

int i1;

for (i1 = 0; i1 <= cf.EncIv.GetUpperBound(0); i1++)








//convert to base64/Radix form

this.TextBox2.Text = Convert.ToBase64String(EncData);

this.Label2.Text = "KEYs and IVs are encrypted by PKCS12 Certificate name: " + uu.ToString() + " and exported to " + myPath + ". Send both of them to intended recipitent." + "so that he can Decrypt it.";



this.TextBox1.ReadOnly = true;

this.Button3.Enabled = true;


//catch (Exception ex)


// Debug.Write (ex.Message);



and getting the error :

Key not valid for use in specified state.

Source Error:

Line 270:             //cf.EncKey = oRSA.Encrypt(Rin.Key, false);
Line 271:            /*Changed the above line to*/
Line 272:            cf.EncKey = oRSA.Encrypt(Rin.Key, false );
Line 273:            cf.EncIv = oRSA.Encrypt(Rin.IV, false);
Line 274:            //comvert to base64 string

Source File: d:\DSCC\DSC 3.5\login.aspx.cs    Line: 272

Stack Trace:

[CryptographicException: Key not valid for use in specified state.
   System.Security.Cryptography.CryptographicException.ThrowCryptogaphicException(Int32 hr) +33
   System.Security.Cryptography.Utils._EncryptKey(SafeKeyHandle hPubKey, Byte[] key) +0
   System.Security.Cryptography.RSACryptoServiceProvider.Encrypt(Byte[] rgb, Boolean fOAEP) +135
   login.Button2_Click(Object sender, EventArgs e) in d:\DSCC\DSC 3.5\login.aspx.cs:272
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565

please Help me its really very urgent. 

May 14, 2009 at 5:45 AM

You're on the wrong forum, I don't think you used the cryptography app block of entlib.


May 14, 2009 at 10:30 AM

Thanks ...

But now my problem is solved...


May 14, 2009 at 1:35 PM

Good to note your problem has been resolved NOW.



May 15, 2009 at 3:34 AM

sure I will post but i have to prepare a proper article for it so that it will be implemented by any one without much deficulty. for that i need some time