Error while decrypting string

Asked

Viewed 4,215 times

3

I have a method to encrypt and decrypt data. I tested it in the Application Console and it works perfectly. When taking this method to the controller, I get following error:

Invalid length for a Base 64 array or string.

This occurs when I place a large string to decrypt (above 30characters +/-). However, I need to traffic a much larger string( encrypted).

I don’t understand why Consolle Application works and MVC( controller), I get this

My method for encrypting and decrypting:

public class Criptografia : ICriptografia
    {

        public Criptografia()
        {
        }


        // Essa seqüência constante é usada como um valor "salt" para as chamadas de função PasswordDeriveBytes .
        // Este tamanho da IV (em bytes) devem = (KeySize / 8). KeySize padrão é 256, portanto, a IV deve ser
        // 32 bytes de comprimento. Usando uma seqüência de 16 caracteres aqui nos dá 32 bytes quando convertido para um array de bytes.
        private static readonly byte[] initVectorBytes = Encoding.ASCII.GetBytes("tu89geji340t89u2");

        // Esta constante é utilizado para determinar o tamanho da chave do algoritmo de encriptação.
        private const int keysize = 256;
        const string senha = "exemplo";


        public static string _Encrypt(string Message)
        {
            byte[] Results;
            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(senha));
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;
            byte[] DataToEncrypt = UTF8.GetBytes(Message);
            try
            {
                ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
                Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
            }
            finally
            {
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }
            return Convert.ToBase64String(Results);
        }


        public string Encrypt(string Message)
        {
            return Criptografia._Encrypt(Message);
        }


        public static string _Decrypt(string Message)
        {
            byte[] Results;
            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(senha));
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;
            byte[] DataToDecrypt = Convert.FromBase64String(Message);
            try
            {
                ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
                Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
            }
            finally
            {
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }
            return UTF8.GetString(Results);
        }


        public  string Decrypt(string Message)
        {
           return Criptografia._Decrypt(Message);
        }

    }
}

The way I use my Controller:

 public ActionResult Dependente(string name)
    {
        Criptografia cr= new Criptografia();   
        string nome = Request.QueryString["name"];

        string nomeDescrypt = cr.Decrypt(nome);
        var dependente =
            dependenteRepository.Dependentes.Where(r => r.sLogin == nomeDescrypt).ToList();
        return View(dependente);

    }

By error, tell me that the length is invalid for Base64, but I do not understand why it works on the console and not on the controller.

  • You should use Firstordefault() instead of Tolist() in the query. This query will return at most 1 record.

  • In this case, it is Tolist(), because I am returning all dependents of this person, only that I was ordered( by superiors) to search by name, and not by ID.

  • Okay. That’s right then.

1 answer

4


As the error message says, a string encoded in base-64 cannot be of any size. The size is always multiple of 4.

What I suspect may be happening is that when you create the URL to Dependente, you are passing the parameter name without escaping or URL-Match. How strings on base-64 commonly end in = (which is a special character and needs to be treated) then the value received in Dependente is arriving corrupted, probably missing the last =.

  • Could you give me an example?

  • Apparently I added: string param = Request.Querystring["param"]; string name = Httputility.Urldecode(param); E worked. I’ll run a few more tests, and I warn you.

  • It all worked out @sergiopereira. Thank you

Browser other questions tagged

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