kennet madsen

kennet madsen

  • NA
  • 5
  • 27.8k

Length of the data to decrypt is invalid. TripleDES

Oct 6 2010 9:12 AM
Hey there...

i am working on some encryption and decryption of a string...
when i encrypt a string it goes fine. but when i right after try to decrypt it i got an:
"Length of the data to decrypt is invalid." error...
it happens when i try to FlushFinalBlock()

here is my code for both encrypt and decrypt:

         public string Encrypt(string plainText)
        {
            UTF8Encoding utf8Encoder = new UTF8Encoding();
            byte[] inputInBytes = utf8Encoder.GetBytes(plainText);
            TripleDESCryptoServiceProvider tdesProvider = new TripleDESCryptoServiceProvider();
            ICryptoTransform cryptoTransform = tdesProvider.CreateEncryptor(symKey, IVKey);
            MemoryStream encryptedStream = new MemoryStream();
            CryptoStream cryptStream = new CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write);

            cryptStream.Write(inputInBytes, 0, inputInBytes.Length);
            cryptStream.FlushFinalBlock();
            encryptedStream.Position = 0;
            byte[] result = new byte[encryptedStream.Length];
            encryptedStream.Read(result, 0, (int)encryptedStream.Length);
            cryptStream.Close();
            return utf8Encoder.GetString(result);
        }

        public string Decrypt(string encryptedString)
        {
            UTF8Encoding utf8Encoder = new UTF8Encoding();
            byte[] enCryptedBytesFromString = utf8Encoder.GetBytes(encryptedString);
            TripleDESCryptoServiceProvider tdesProvider = new TripleDESCryptoServiceProvider();
            ICryptoTransform cryptoTransform = tdesProvider.CreateDecryptor(symKey, IVKey);
            MemoryStream encryptedStream = new MemoryStream();
            CryptoStream cryptStream = new CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write);

            cryptStream.Write(enCryptedBytesFromString, 0, enCryptedBytesFromString.Length);
            cryptStream.FlushFinalBlock();
            encryptedStream.Position = 0;
            byte[] result = new byte[encryptedStream.Length];
            encryptedStream.Read(result, 0, (int)encryptedStream.Length);
            cryptStream.Close();
            return utf8Encoder.GetString(result);
        }

Can anyone see what i am doing wrong?

Regards
Kennet Madsen

Answers (5)