Reputation: 22696
C# 2008
I am using the following code to encrypt and encrypt a message. However, when I attempt to decrypt I get a 'Bad Data' error.
Is there anything wrong with my code below?
Many thanks,
public string encryptText(string text)
{
try
{
TripleDESCryptoServiceProvider encrypt = new TripleDESCryptoServiceProvider();
encrypt.Key = new byte[] { 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 144, 89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 0 };
encrypt.IV = new byte[] { 1, 2, 3, 5, 8, 13, 21, 34 };
byte[] byteText = Encoding.Unicode.GetBytes(text);
ICryptoTransform encryptor = encrypt.CreateEncryptor();
byte[] encryptedText = encryptor.TransformFinalBlock(byteText, 0, byteText.Length);
return Encoding.Unicode.GetString(encryptedText);
}
catch (Exception ex)
{
Console.Write(ex.Message);
return ex.Message;
}
}
/// Decrypt the text
public string decryptText(string encryptedText)
{
try
{
byte[] bytesText = Encoding.Unicode.GetBytes(encryptedText);
TripleDESCryptoServiceProvider decrypt = new TripleDESCryptoServiceProvider();
decrypt.Key = new byte[] { 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 144, 89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 0 };
decrypt.IV = new byte[] { 1, 2, 3, 5, 8, 13, 21, 34 };
ICryptoTransform decryptor = decrypt.CreateDecryptor();
byte[] originalText = decryptor.TransformFinalBlock(bytesText, 0, encryptedText.Length);
return Encoding.Unicode.GetString(originalText);
}
catch (Exception ex)
{
Console.Write(ex.Message);
return ex.Message;
}
}
Upvotes: 0
Views: 3624
Reputation: 3194
Yup, there are a few mistakes in the code.
encryptedText and bytesText must be the same byte array. As Jon Skeet suggest you could use Base64 encoding.
The IV is part of the ciphertext. Hence you don't have to set the IV when you decrypt.
The default mode of encryption is CBC. This mode requires that IV is random (rsp. unpredictable). Hence you must not set a fixed IV, when you encrypt. When you create the CryptoServiceProvider a random IV is already set. Hence overwritting the IV with a fixed value decreases your security.
Putting a key explicitly in the code isn't a great idea. I hope you'll change this once your code leaves the experimental state.
Is there a reason to use TripleDes? Otherwise you might want to consider using AES instead.
Upvotes: 1
Reputation: 1503729
You're taking the encrypted bytes and converting them to a string using Encoding.Unicode
, but then you're taking the string and converting it back to bytes using Encoding.Default
. That's pretty much guaranteed not to work (unless the default happens to be UTF-16).
However, you should use either of these - converting arbitrary binary data to text using an encoding is a bad idea. Use Convert.ToBase64String
(in the encryptor) and Convert.FromBase64String
(in the decryptor) instead.
(I'd also very much query the wisdom of returning an exception message as if it were the successful result of encrypting/decrypting, but hopefully you only did that for the sake of the sample code.)
Upvotes: 5