0

I have a rather simple code for encryption and decryption. However, when I encrypt then decrypt, the output is not what I originally input.

This is the encryption:

static byte[] Encrypt(SymmetricAlgorithm aesAlg, string plainText)
    {
        ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

        using (MemoryStream msEncrypt = new MemoryStream())
        {
            using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            {
                using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                {
                    swEncrypt.Write(plainText);
                }
                return msEncrypt.ToArray();
            }
        }
    }

Decryption:

static string Decrypt(SymmetricAlgorithm aesAlg, byte[] cipherText)
    {
        ICryptoTransform decryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

        using (MemoryStream msDecrypt = new MemoryStream(cipherText))
        {
            using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
            {
                using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                {
                    return srDecrypt.ReadToEnd();
                }
            }
        }
    }

Main:

public static void Main()
    {
        string original = "My secret data!";

        using (SymmetricAlgorithm symmetricAlgorithm = new AesManaged())
        {
            byte[] encrypted = Encrypt(symmetricAlgorithm, original);
            string roundtrip = Decrypt(symmetricAlgorithm, encrypted);

            Console.WriteLine("Original: {0}", original);
            Console.WriteLine("RoundTrip: {0}", roundtrip);
        }
    }

Ouput should be:

Original: My secret data!
RoundTrip: My secret data!

However, it comes out as:

Original: My secret data!
RoundTrip: ">�����6dB&JD䮦�L�ܹ�SKo\v*.�"

or something funny like that.

I couldn't find anything helpful on the internet. Any suggestions are greatly appreciated.

mmking
  • 1,564
  • 4
  • 26
  • 36

2 Answers2

1

The problem is that in your Decrypt method you create another encryptor, not a Decryptor!

If you change the line

aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

to

aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

Then you will get the decypted text.

Joey Ciechanowicz
  • 3,345
  • 3
  • 24
  • 48
-1

Decryption code

static string Decrypt(SymmetricAlgorithm aesAlg, byte[] cipherText)
{
    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

    using (MemoryStream msDecrypt = new MemoryStream(cipherText))
    {
        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
        {
            using (StreamReader srDecrypt = new StreamReader(csDecrypt))
            {
                return srDecrypt.ReadToEnd();
            }
        }
    }
}
Sarvesh Mishra
  • 2,014
  • 15
  • 30