"Invalid Data" error when trying to decrypt a file using TripleDES

3

I am developing a routine that decrypts information from a ".txt" document using TripleDES.

However when decrypting it it generates the following error:

  

Invalid data.

In StackTrace it looks like this:

  

in   System.Security.Cryptography.CryptographicException.ThrowCryptographicException (Int32   hr) in   System.Security.Cryptography.Utils._DecryptData (SafeKeyHandle hKey,   Byte [] data, Int32 ib, Int32 cb, Byte [] & outputBuffer, Int32   outputOffset, PaddingMode, PaddingMode, Boolean fDone) in   System.Security.Cryptography.CryptoAPITransform.TransformFinalBlock (Byte []   inputBuffer, Int32 inputOffset, Int32 inputCount) into   System.Security.Cryptography.CryptoStream.Read (Byte [] buffer, Int32   offset, Int32 count) in   CryptographyPortabilidadeTeste.CriptografarXML_3DES.DecryptTextFromMemory (Byte []   Data, Byte [] Key, Byte [] IV) in d: \ Projects \ Internal Systems   Cecresp \ CryptographyPortability Test \ EncryptionPortability Test \ EncryptXML_3DES.cs: line   180

Follow the code for a better understanding, event:

    private void btnDescriptografar_Click(object sender, EventArgs e)
    {
        try
        {
            TripleDES tripleDESalg = TripleDES.Create();

            // Nome do arquivo completo.
            string FileName = txtbArquivo.Text;

            using (StreamReader sr = File.OpenText(FileName))
            {
                string path = @"c:\testeDescriptografado3DES.txt";

                using (StreamWriter sw = File.CreateText(path))
                {
                    string s = "";
                    while ((s = sr.ReadLine()) != null)
                    {
                        byte[] linhaBytes = new byte[s.Split('-').Count()];
                        int i = 0;
                        foreach (var item in s.Split('-'))
                        {
                            linhaBytes[i] = Convert.ToByte(item);
                            i++;
                        }

                        //Criptografia da string para dentro da memória buffer
                        string resultado = DecryptTextFromMemory(linhaBytes, tripleDESalg.Key, tripleDESalg.IV);

                        //Escrita para um novo arquivo.
                        sw.WriteLine(resultado);
                    }
                }
            }

            MessageBox.Show("Arquivo descriptografado");
        }
        catch (Exception exc)
        {
            MessageBox.Show(exc.Message);
        }
    }

Method "DecryptTextFromMemory ()":

    public string DecryptTextFromMemory(byte[] Data, byte[] Key, byte[] IV)
    {
        try
        {
            MemoryStream msDecrypt = new MemoryStream(Data);

            TripleDES tripleDESalg = TripleDES.Create();

            CryptoStream csDecrypt = new CryptoStream(msDecrypt,tripleDESalg.CreateDecryptor(Key, IV),CryptoStreamMode.Read);

            byte[] fromEncrypt = new byte[Data.Length];

            //AQUI DISPARA-SE O ERRO!!!
            csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

            return new ASCIIEncoding().GetString(fromEncrypt);
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            return null;
        }
    } 

What is the reason for this error?

    
asked by anonymous 29.05.2014 / 20:41

1 answer

1

The error occurred on this line: linhaBytes[i] = Convert.ToByte(item);

Proof:

According to documentation the string must contain apenas números .

What do you think about converting your string to a Byte[] like this:

byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(yourString);

Source: Here

    
29.05.2014 / 21:05