DES-ECB encryption and decryption

Cracker picture Cracker · Jul 24, 2011 · Viewed 8.9k times · Source

I'm using DES-ECB + base64 encryption in my application. That's the code of the class I called "Crypto"

public class Crypto
{

    public static string Decrypt(string encryptedString)
    {
        DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();
        desProvider.Mode = CipherMode.ECB;
        desProvider.Padding = PaddingMode.PKCS7;
        desProvider.Key = Encoding.ASCII.GetBytes("e5d66cf8");
        using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(encryptedString)))
        {
            using (CryptoStream cs = new CryptoStream(stream, desProvider.CreateDecryptor(), CryptoStreamMode.Read))
            {
                using (StreamReader sr = new StreamReader(cs, Encoding.ASCII))
                {
                    return sr.ReadToEnd();
                }
            }
        }
    }

    public static string Encrypt(string decryptedString)
    {
        DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();
        desProvider.Mode = CipherMode.ECB;
        desProvider.Padding = PaddingMode.PKCS7;
        desProvider.Key = Encoding.ASCII.GetBytes("e5d66cf8");
        using (MemoryStream stream = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(stream, desProvider.CreateEncryptor(), CryptoStreamMode.Write))
            {
                byte[] data = Encoding.Default.GetBytes(decryptedString);
                cs.Write(data, 0, data.Length);
                return Convert.ToBase64String(stream.ToArray());
            }
        }
    }
}

but when I encrypt a string, then decrypt it again and encrypt one more time, the encrypted string is not the same as previous encrypted was. So that's the first encrypted string:

kEN0HUp/dqz8kXA7nYivJG6Jl3haLJjhBq1UfEtQTwaPwizW//03M0UxF8dBuYZo2BoZ5vsVcXRJF1LpFZLWxDsdeKAC43L2K2OoYRxTn/dA6KmM13YS9xOezGiROQfVj5qrkdokJRCvj0gYfFoH2oeDGyN+EAw5Dgzsp697kj4=

and here comes the second encrypted string:

kEN0HUp/dqz8kXA7nYivJG6Jl3haLJjhBq1UfEtQTwaPwizW//03M0UxF8dBuYZo2BoZ5vsVcXRJF1LpFZLWxDsdeKAC43L2K2OoYRxTn/dA6KmM13YS9xOezGiROQfVj5qrkdokJRCvj0gYfFoH2oeDGyN+EAw5

They are almost same, except this "Dgzsp697kj4=" in the first string.
What's wrong?
Thanks in advance.

Answer

Rasmus Faber picture Rasmus Faber · Jul 24, 2011

You are losing data. In your Encrypt() method you need to call EncryptFinalBlock() to let the padding algorithm know that you are done so that it can add the padding:

using (CryptoStream cs = new CryptoStream(stream, desProvider.CreateEncryptor(), CryptoStreamMode.Write))
{
  byte[] data = Encoding.Default.GetBytes(decryptedString);
  cs.Write(data, 0, data.Length);
  cs.FlushFinalBlock(); // <-- Add this
  return Convert.ToBase64String(stream.ToArray());
}