all groups > dotnet security > june 2006 >
You're in the

dotnet security

group:

Bad Data with DES Decryption


Bad Data with DES Decryption Steve Telford
6/18/2006 9:03:02 PM
dotnet security: Hello everyone,
I am using the following class to encrypt/decrypt a string using C# in .NET
Framework 2.0. When I call decrypt (in testing, straight after calling
encrypt) I get a 'Bad Data' Cryptographic Exception.

Can anyone offer any advice as to where I may be going wrong?

Thanks in advance.

public class CryptoUtil
{
private static byte[] KEY_64 = { 12, 58, 77, 34, 92, 28, 73, 41 };
private static byte[] IV_64 = { 48, 67, 82, 10, 78, 63, 91, 25 };

public CryptoUtil()
{
}

public static string encrypt(string sPlainText)
{
if (sPlainText != "")
{
DESCryptoServiceProvider dcsp = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms,
dcsp.CreateEncryptor(KEY_64, IV_64),
CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cs);

sw.Write(sPlainText);
sw.Flush();
cs.FlushFinalBlock();
ms.Flush();

return Convert.ToBase64String(ms.GetBuffer(), 0,
(int)(ms.Length));
}
return "";
}

public static string decrypt(string sCypherText)
{
if (sCypherText != "")
{
DESCryptoServiceProvider dcsp = new DESCryptoServiceProvider();

byte[] buffer = Convert.FromBase64String(sCypherText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms,
dcsp.CreateDecryptor(KEY_64, IV_64),
CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cs);

return sr.ReadToEnd();
}
return "";
}
Re: Bad Data with DES Decryption Steve Telford
6/19/2006 3:56:02 PM
Thank you very much Pieter.
Sometimes the simplest answers are staring you right in the face! I spent
hours looking at this, and still missed it!!

[quoted text, click to view]
Re: Bad Data with DES Decryption Pieter Philippaerts
6/19/2006 11:24:58 PM
[quoted text, click to view]

In the above method you decode the Base64 string into a byte array, and then
do nothing with the result (buffer isn't used anymore after the call to
FromBase64String). You probably forgot to initialize the MemoryStream with
the buffer..?

Regards,
Pieter Philippaerts

Re: Bad Data with DES Decryption Joe Kaplan (MVP - ADSI)
6/19/2006 11:37:23 PM
Note that using a fixed IV is a bad practice. It should be random. It is
ok to include it with the cipher text (perhaps as the first X bytes of the
encrypted data), but you really do want it to be random.

Joe K.

--
Joe Kaplan-MS MVP Directory Services Programming
Co-author of "The .NET Developer's Guide to Directory Services Programming"
http://www.directoryprogramming.net
--
[quoted text, click to view]

AddThis Social Bookmark Button