Showing posts with label Encrypt And Decrypt Using Digital Signatures. Show all posts
Showing posts with label Encrypt And Decrypt Using Digital Signatures. Show all posts

Thursday, June 11, 2009

Encrypt And Decrypt Using Digital Signatures

Encrypt And Decrypt Using Digital Signatures


Now in continutaion to my earlier artcile the mirroe link of the article here I am going to describe how we can use the digital signatures for the purpose of Encryption and Decryption.

The Following code will show how we can encrypt the plain text.

Encryption


#region Encryption

public string GetEncryptedText(string PlainStringToEncrypt)

{

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)

{

throw e;

}

}
#endregion

Now once we have encrypted text we need to decrypt it. the following section of code will demonstrate how to decrypt that encrypted text.

Decryption


#region Decryption

public string GetDecryptedText(string EncryptedStringToDecrypt)

{

try

{



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)

{

return e.Message;

}

}

catch

{

return EncryptedStringToDecrypt;

}

}
#endregion



Thanks and Regards

Meetu Choudhary

Subscribe via email

Enter your email address:

Delivered by FeedBurner

MSDotnetMentor

MSDotnetMentor My Website http://msdotnetmentor.com