AES加密无效填充

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AES加密无效填充相关的知识,希望对你有一定的参考价值。

我正在尝试转换以前使用256字节密钥处理AES加密的工作脚本。我试图让脚本使用128bye,但我得到填充无效,并且无法在第110行删除错误。任何帮助或提示都会有所帮助。

我尝试过使用keySize或块大小但尚未使用它。

这是代码。

using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {        

     //   Response.Write(timeNow.ToString());

        string str = @"{""dataset"":{""schema"" :{""manifest"":{""datasetname"":""/Apps/SM/Custom/Shoppers/ShopperMailbox_GetAssignedInstances"",""datafieldsmode"":""D"",""dbsqltype"":""P"",""schemaformat"":""JSON"",""dataformat"":""json"",""encoding"":""utf-8"",""security"":{},""cacheable"":{},""hasoutputparameters"":false,""meta"":{}},""parameters"":[{""name"":""SecurityObjectUserID"",""heading"":""SecurityObjectUserID"",""headingglobalizationenabled"":true,""sqlparamname"":""@SecurityObjectUserID"",""datatype"":""bigint"",""datatypecharlength"":null,""datatypenumericprecision"":19,""datatypenumericprecisionradix"":10,""datatypenumericscale"":0,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":1,""direction"":null,""lookup"":null},{""name"":""ShopperPhoneNumber"",""heading"":""ShopperPhoneNumber"",""headingglobalizationenabled"":true,""sqlparamname"":""@ShopperPhoneNumber"",""datatype"":""varchar"",""datatypecharlength"":63,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":2,""direction"":null,""lookup"":null},{""name"":""ShopperEmailAddress"",""heading"":""ShopperEmailAddress"",""headingglobalizationenabled"":true,""sqlparamname"":""@ShopperEmailAddress"",""datatype"":""nvarchar"",""datatypecharlength"":222,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":3,""direction"":null,""lookup"":null},{""name"":""MiscSettings"",""heading"":""MiscSettings"",""headingglobalizationenabled"":true,""sqlparamname"":""@MiscSettings"",""datatype"":""nvarchar"",""datatypecharlength"":-1,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":4,""direction"":null,""lookup"":null}],""columns"":[{""name"":""Shopper Email Address"",""heading"":""Shopper Email Address"",""headingglobalizationenabled"":true,""sqlparamname"":null,""datatype"":""nvarchar"",""datatypecharlength"":222,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":0,""direction"":null,""lookup"":null},{""name"":""Instance ID"",""heading"":""Instance ID"",""headingglobalizationenabled"":true,""sqlparamname"":null,""datatype"":""bigint"",""datatypecharlength"":null,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":1,""direction"":null,""lookup"":null},{""name"":""Location Street Address"",""heading"":""Location Street Address"",""headingglobalizationenabled"":true,""sqlparamname"":null,""datatype"":""nvarchar"",""datatypecharlength"":150,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":2,""direction"":null,""lookup"":null},{""name"":""Location City"",""heading"":""Location City"",""headingglobalizationenabled"":true,""sqlparamname"":null,""datatype"":""nvarchar"",""datatypecharlength"":50,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":3,""direction"":null,""lookup"":null},{""name"":""Location State"",""heading"":""Location State"",""headingglobalizationenabled"":true,""sqlparamname"":null,""datatype"":""nvarchar"",""datatypecharlength"":8,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":4,""direction"":null,""lookup"":null},{""name"":""Location Postal Code"",""heading"":""Location Postal Code"",""headingglobalizationenabled"":true,""sqlparamname"":null,""datatype"":""nvarchar"",""datatypecharlength"":12,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":5,""direction"":null,""lookup"":null},{""name"":""Client Name"",""heading"":""Client Name"",""headingglobalizationenabled"":true,""sqlparamname"":null,""datatype"":""nvarchar"",""datatypecharlength"":200,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":6,""direction"":null,""lookup"":null},{""name"":""Survey Title"",""heading"":""Survey Title"",""headingglobalizationenabled"":true,""sqlparamname"":null,""datatype"":""nvarchar"",""datatypecharlength"":500,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":7,""direction"":null,""lookup"":null},{""name"":""Planned Date"",""heading"":""Planned Date"",""headingglobalizationenabled"":true,""sqlparamname"":null,""datatype"":""date"",""datatypecharlength"":null,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":8,""direction"":null,""lookup"":null},{""name"":""Due Date"",""heading"":""Due Date"",""headingglobalizationenabled"":true,""sqlparamname"":null,""datatype"":""datetime"",""datatypecharlength"":null,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":9,""direction"":null,""lookup"":null},{""name"":""Campaign"",""heading"":""Campaign"",""headingglobalizationenabled"":true,""sqlparamname"":null,""datatype"":""nvarchar"",""datatypecharlength"":50,""datatypenumericprecision"":null,""datatypenumericprecisionradix"":null,""datatypenumericscale"":null,""datatypedatetimeprecision"":null,""allownulls"":true,""defaultvalue"":null,""controlvisual"":{},""validator"":{},""ordinalposition"":10,""direction"":null,""lookup"":null}]},""data"":[{""Shopper Email Address"":""frecklegami8@gmail.com"",""Instance ID"":416722,""Location Street Address"":""2700 Potomac Mills Circle"",""Location City"":""Woodbridge"",""Location State"":""VA"",""Location Postal Code"":""22192"",""Client Name"":""Christmas Tree Shops "",""Survey Title"":""CTS In Store Mystery Shop"",""Planned Date"":null,""Due Date"":""2018-01-17 00:59:00"",""Campaign"":""2018-01""},{""Shopper Email Address"":""frecklegami8@gmail.com"",""Instance ID"":418529,""Location Street Address"":""4830 Crossings Court"",""Location City"":""Massaponax"",""Location State"":""VA"",""Location Postal Code"":""22407"",""Client Name"":""Steak 'N Shake - Virginia"",""Survey Title"":""Steak 'N Shake Dine In Evaluation v2"",""Planned Date"":null,""Due Date"":""2018-01-20 23:59:00"",""Campaign"":""2018-01""}]}}";
        string encryptedString = AESEncryption.Encrypt(str, "ds!5da%-0sadg$!$2fDUC-51AHB)!"); //, "ASDdasdsa213DSA#4!#@!#@dsadsa", "SHA512", 10000, IV);
        Response.Write(encryptedString);
        //Response.Write("<br/>");
        //Response.Write("<br/>");
        //Response.Write("<br/>");
        //Response.Write("<br/>");
        encryptedString = @"dFmyMsfNxzWqVqfYG14ueWRrxA2EezLcatVo9127uRpFZEnYepm9yXv2SQpD+UtX5Fuag9mpJrQL1I0QX7KSGp87TrEH0y6PXlLsjbXSO8hIv0XybmaxAS0/xKmkCdxz";
         Response.Write(AESEncryption.Decrypt(encryptedString, "ds!5da%-0sadg$!$2fDUC-51AHB)!")); //, "ASDdasdsa213DSA#4!#@!#@dsadsa", "SHA512", 10000, IV));
    }
}

public static class AESEncryption
{
    #region Static Functions

    // This constant is used to determine the keysize of the encryption algorithm in bits.
    // We divide this by 8 within the code below to get the equivalent number of bytes.
    private const int Keysize = 128;

    // This constant determines the number of iterations for the password bytes generation function.
    private const int DerivationIterations = 100000;

    public static string Encrypt(string plainText, string passPhrase)
    {
        // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
        // so that the same Salt and IV values can be used when decrypting.  
        var saltStringBytes = Generate256BitsOfRandomEntropy();
        var ivStringBytes = Generate256BitsOfRandomEntropy();
        var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
        {
            var keyBytes = password.GetBytes(Keysize / 8);
            using (var symmetricKey = new RijndaelManaged())
            {
                symmetricKey.BlockSize = 128;
                symmetricKey.Mode = CipherMode.CBC;
                symmetricKey.Padding = PaddingMode.PKCS7;
                using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                            cryptoStream.FlushFinalBlock();
                            // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                            var cipherTextBytes = saltStringBytes;
                            cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                            cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                            memoryStream.Close();
                            cryptoStream.Close();
                            return Convert.ToBase64String(cipherTextBytes);
                        }
                    }
                }
            }
        }
    }

    public static string Decrypt(string cipherText, string passPhrase)
    {
        // Get the complete stream of bytes that represent:
        // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
        if (String.IsNullOrEmpty(cipherText))
        {
            return "Empty string";
        }

        if (!IsBase64String(cipherText))
        {
            return "Not a valid Base64 string";
        }
        var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
        // Get the saltbytes by extracting the first 16 bytes from the supplied cipherText bytes.
        var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
        // Get the IV bytes by extracting the next 16 bytes from the supplied cipherText bytes.
        var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
        // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
        var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 5)).ToArray();

        using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
        {
            var keyBytes = password.GetBytes(Keysize / 8);
            using (var symmetricKey = new RijndaelManaged())
            {
                symmetricKey.BlockSize = 128;
                symmetricKey.Mode = CipherMode.CBC;
                symmetricKey.Padding = PaddingMode.PKCS7;
                using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
                {
                    using (var memoryStream = new MemoryStream(cipherTextBytes))
                    {
                        using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                        {
                            var plainTextBytes = new byte[cipherTextBytes.Length];
                            var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                            memoryStream.Close();
                            cryptoStream.Close();
                            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                        }
                    }
                }
            }
        }
    }

    private static byte[] Generate256BitsOfRandomEntropy()
    {
        var randomBytes = new byte[16]; // 16 Bytes will give us 128 bits.
        using (var rngCsp = new RNGCryptoServiceProvider())
        {
            // Fill the array with cryptographically secure random bytes.
            rngCsp.GetBytes(randomBytes);
        }
        return randomBytes;
    }



    private static bool IsBase64String(string value)
    {
        if (string.IsNullOrEmpty(value))
        {
            return false;
        }

        // if(value == null || value.Length == 0 || value.Length % 4 != 0 || value.Contains(" ") || value.Contains("	") || value.Contains("
") || value.Contains("
"))
        // {
        // return false;
        // }

        try
        {
            Convert.FromBase64String(value);
            return true;
            //if (value.EndsWith("="))
            //{
            //    value = value.Trim();
            //    int mod4 = value.Length % 4;
            //    if (mod4 != 0)
            //    {
            //        return false;
            //    }
            //    return true;
            //}
            //else
            //{

            //    return false;
            //}
        }
        catch (FormatException)
        {
            return false;
        }
    }

    public static string Left(this string value, int maxLength)
    {
        if (string.IsNullOrEmpty(value)) return value;
        maxLength = Math.Abs(maxLength);

        return (value.Length <= maxLength
               ? value
               : value.Substring(0, maxLength)
               );
    }

    #endregion
}
答案

你有这一行的错误:

var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 5)).ToArray();

为什么你只采用cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 5)字节?正如我在加密算法中看到的那样,在去除盐和IV后剩余的所有字节都应该被采用。

即用。替换

var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).ToArray();

和解密将工作正常。

UPD:删除你的硬编码encodedString并尝试解密以前生成的字符串。看来您的硬编码字符串是使用不同的算法加密的。

以上是关于AES加密无效填充的主要内容,如果未能解决你的问题,请参考以下文章

C#:AES 错误:填充无效且无法删除。相同的钥匙和一切,帮助

aes算法填充方式

如何在 Flutter 中使用填充“ISO10126”进行 AES 加密?

AES 加密在 iOS 13.4 上无法正常工作

AES 加密位: 128位,加密模式:CBC, 填充模式:Zeros

AES模式和填充