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
Good one !!!
ReplyDeletegood one !
ReplyDeleteIs this code of c++ or something else i am not sure but as sytax may be different for languages but logic remains same so i could understand this.And its really informative about digital signature certificate
ReplyDelete