0

I have recently been experimenting with the "CryptoStream", and ran into the idea of encrypting & decrypting a text via. the Aes class. 'Namespace: System.Security.Cryptography'

After making a function that succesfully encrypted a text using two input parameters: Text, Password

static byte[] Salt = { 18,39,27,48,82,32,12,92 };
        public static string EncryptAES(string txt, string Password) {
            Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(Password, Salt);
            RijndaelManaged RJM = new RijndaelManaged();
            RJM.Key = rfc.GetBytes(RJM.KeySize / 8);
            ICryptoTransform ICT = Aes.Create().CreateEncryptor(RJM.Key, RJM.IV);

            using (MemoryStream MS = new MemoryStream()) {
                using (CryptoStream CS = new CryptoStream(MS, ICT, CryptoStreamMode.Write)) {
                    using (StreamWriter SW = new StreamWriter(CS)) {
                        SW.Write(txt);
                    }
                }

                return Convert.ToBase64String(MS.ToArray());
            }
        }

The issue of decrypting the text took place.

My attempt of decrypt the text was the following:

public static string DecryptAES(string EncryptedTxt, string Password) {
            Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(EncryptedTxt, Salt);
            RijndaelManaged RJM = new RijndaelManaged();
            RJM.Key = rfc.GetBytes(RJM.KeySize / 8);
            ICryptoTransform ICT = Aes.Create().CreateDecryptor(RJM.Key, RJM.IV);
            using (MemoryStream MS = new MemoryStream(Convert.FromBase64String(EncryptedTxt))) {
                using (CryptoStream CS = new CryptoStream(MS, ICT, CryptoStreamMode.Read)) {
                    using (StreamReader SR = new StreamReader(CS)) {
                        return SR.ReadToEnd();
                    }
                }
            }

However; it appears that my way of converting the memorystream to string and then back was invaild, as I get the following error: Error: Value cannot be null\nParameter name: inputBuffer

The error occurs at using (MemoryStream MS = new MemoryStream(Convert.FromBase64String(EncryptedTxt)))

How can I converter the MemoryStream into string and back?

Thanks in advance :-)

Rasmus Søborg
  • 3,597
  • 4
  • 29
  • 46
  • First thing I notice is that you're not using the salt correctly. A salt should not be constant. I'd create a random salt, and prepend it to the output. Same procedure for the IV. – CodesInChaos Aug 26 '12 at 11:00
  • One clear mistake is that you use a different IV for decryption than for encryption (It's random both times). You need to use a random one for encryption, and prepend it to the ciphertext. – CodesInChaos Aug 26 '12 at 11:03

0 Answers0