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

Asked

Viewed 1,347 times

3

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

But when decrypting it generates the following error:

Invalid data.

Stacktrace is like this:

in System.Security.Cryptography.CryptographicException.Throwcryptographicexception(Int32 hr) in System.Security.Cryptography.Utils. _Decryptdata(Safekeyhandle hKey, Byte[] date, Int32 Ib, Int32 cb, Byte[]& outputBuffer, Int32 outputOffset, Paddingmode Paddingmode, Boolean fDone) in System.Security.Cryptography.CryptoAPITransform.Transformfinalblock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) in System.Security.Cryptography.CryptoStream.Read(Byte[] buffer, Int32 offset, Int32 Count) in Encryptionportabilitieste.Encryptionxml_3des.Decrypttextfrommemory(Byte[] Data, Byte[] Key, Byte[] IV) na d: Internal Systems Projects Cecresp Cryptologythis Encryptionthis Encryptionthis Encryptionxml_3des.Cs:line 180

Follow code for 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?

  • I don’t understand this line here: csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);. fromEncrypt at this point is empty in theory. It was not to read from Data?

  • Could send the lines of the file in question?

  • Gypsy, in case the "csDecrypt" holds the "msDecrypt", which holds the "Date". Understood?

  • @Reiksiel, the file I’m using is test. It has 3 lines with 3 random names. Nothing too much

  • @Matheusbessa, I found this link https://go4answers.webhost4life.com/Example/cryptographicexception-bad-data-209425.aspx. I could check, I think it might help?

1 answer

1

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

Proof:

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

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

How do you feel about converting your string to one Byte[] thus:

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

Source: Here

  • No, no... The error is not triggered there. And when the I enters the method, u can see the array of filled bytes correctly. I am searching the class "Cryptostream" I think the error is there.

  • 1

    @Matheusbessa, sorry my error occurred on the informed line. Could you pass me the lines of the file you used to simulate?

  • Sorry @Reiksiel, something got misinformed, rs. My encrypted file has the following format: "233-12-100-24-52". Then the split, separates into array and then assigns to the array for each item. I had misunderstood its first question. Sorry, my fault.

  • Test with this sequence of bytes on a txt: "9-182-191-15-62-72-246-246-52-75-202-159-101-239-66-98-41-244-99-101-189-140-47-91-20-113-22-99-74-118-251-174".

  • 1

    @Matheusbessa, from the error reading when filling position 22 of the array at value 47, I will try without it ok?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.