Encryption or Decryption using TripleDES
private string TripleDESEncrypt(string tbMessage)
{
try
{
TripleDES threedes = new TripleDESCryptoServiceProvider();
threedes.Key = StringToByte(tbKey, 24); // convert to 24 characters - 192 bits
threedes.IV = StringToByte("12345678");
byte[] key = threedes.Key;
byte[] IV = threedes.IV;
ICryptoTransform encryptor = threedes.CreateEncryptor(key, IV);
MemoryStream msEncrypt = new MemoryStream();
CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
// Write all data to the crypto stream and flush it.
csEncrypt.Write(StringToByte(tbMessage), 0, StringToByte(tbMessage).Length);
csEncrypt.FlushFinalBlock();
// Get the encrypted array of bytes.
byte[] encrypted = msEncrypt.ToArray();
return ByteToString(encrypted);
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
private string TripleDESDecrypt(string encryptedMessage)
{
try
{
TripleDES threedes = new TripleDESCryptoServiceProvider();
threedes.Key = StringToByte(tbKey, 24); // convert to 24 characters - 192 bits
threedes.IV = StringToByte("12345678");
byte[] key = threedes.Key;
byte[] IV = threedes.IV;
ICryptoTransform decryptor = threedes.CreateDecryptor(key, IV);
// Now decrypt the previously encrypted message using the decryptor
byte[] encrypted = StringToByteDecimal(encryptedMessage);
MemoryStream msDecrypt = new MemoryStream(encrypted);
CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
return ByteToString(csDecrypt);
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
Comments
Post a Comment