AES decryption error “ The input data is not a complete block.” Error vb.net

前端 未结 3 672
你的背包
你的背包 2021-01-26 04:35

I keep getting this \"The input data is not a complete block.\" error while decrypting. The function successfully encrypts plain text and puts the IV in a textbox. I am using t

3条回答
  •  心在旅途
    2021-01-26 05:08

    Unless you are going to manually make sure your input is in multiples of BlockSize (in bits), make sure to specify a padding:

    Example code:

    byte[] Process(byte[] bInput, bool decrypt = false)
    {
        byte[] bOutput = null;
    
        using (var c = System.Security.Cryptography.AesCryptoServiceProvider.Create())
        {
            c.BlockSize = 128;
            c.IV = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf }; // blocksize / 8 = 16 long
            c.KeySize = 256;
            c.Key = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf }; // key = keysize / 8 = 32 bytes
            c.Mode = System.Security.Cryptography.CipherMode.CBC;
            c.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            if (decrypt)
            {
                using (var t = c.CreateDecryptor())
                {
                    bOutput = t.TransformFinalBlock(bInput, 0, bInput.Length);
                }
            }
            else
            {
                using (var t = c.CreateEncryptor())
                {
                    bOutput = t.TransformFinalBlock(bInput, 0, bInput.Length);
                }
            }
        }
    
        return bOutput;
    }
    

提交回复
热议问题