填充无效,不能删除AES PKCS7



我正在尝试测试一个简单的类以加密C#中的数据。

`

{  [TestFixture]
    public class CryptTest
    {
        [Test]
        public void TestMethod()
        {
            String text = "Hello World!";
            String crypt = EncryptionService.Encrypt(text, Config.KEY_STRING);
            Console.WriteLine(crypt);
            String clear = EncryptionService.Decrypt(crypt, Config.KEY_STRING);
            Console.WriteLine(clear);
            Assert.That(clear, Is.EqualTo(text));

        }

`但是,我收到以下例外:

Message: System.Security.Cryptography.CryptographicException : Padding is invalid and cannot be removed.

与堆栈:

        StackTrace  "   at System.Security.Cryptography.CapiSymmetricAlgorithm.DepadBlock(Byte[] block, Int32 offset, Int32 count)rn   at System.Security.Cryptography.CapiSymmetricAlgorithm.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)rn   at System.Security.Cryptography.CryptoStream.Read(Byte[] buffer, Int32 offset, Int32 count)rn   at System.IO.StreamReader.ReadBuffer()rn   at System.IO.StreamReader.ReadToEnd()rn   at InsuranceMidAm.Services.EncryptionService.Decrypt(String cipher, String key) in C:\Visual Studio Projects\InsuranceMidAm\InsuranceMidAm\Services\EncryptionService.cs:line 72rn   at InsuranceMidAm.Tests.CryptTest.TestMethod() in C:\Visual Studio Projects\InsuranceMidAm\InsuranceMidAm.Tests\CryptTest.cs:line 20" string

这是正在测试的类:

namespace InsuranceMidAm.Services
{
    public class EncryptionService
    {
        // Reference: https://stackoverflow.com/questions/273452/using-aes-encryption-in-c-sharp
        public static String Encrypt(String text, String key)
        {
            byte[] value = UTF8Encoding.UTF8.GetBytes(text);
            byte[] crypt;
            byte[] iv;
            using (Aes myAes = Aes.Create())
            {
                myAes.KeySize = 256;
                myAes.Mode = CipherMode.CBC;
                myAes.Key = HexToBin(key);
                myAes.GenerateIV();
                myAes.Padding = PaddingMode.PKCS7;
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, myAes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(value, 0, value.Length);
                        cs.FlushFinalBlock();
                        crypt = ms.ToArray();
                    }
                }
                iv = myAes.IV;
                myAes.Clear();
            }
            return ByteArrayToString(crypt) + ":" + ByteArrayToString(iv);
        }
        public static string Decrypt(String cipher, String key)
        {
            String outputString = "";
            byte[] ivBytes = HexToBin(getIV(cipher));
            byte[] valBytes = HexToBin(getSSN(cipher));
            using (Aes myAes = Aes.Create())
            {
                int size = valBytes.Count();
                myAes.KeySize = 256;
                myAes.Mode = CipherMode.CBC;
                myAes.Key = HexToBin(key);
                myAes.IV = ivBytes;
                myAes.Padding = PaddingMode.PKCS7;
                char[] output = new char[256];
                ICryptoTransform myDecrypter = myAes.CreateDecryptor(myAes.Key, myAes.IV);
                using (MemoryStream memory = new MemoryStream(ivBytes))
                {
                    using (CryptoStream cryptStream = new CryptoStream(memory, myDecrypter, CryptoStreamMode.Read))
                    {
                        using (StreamReader reader = new StreamReader(cryptStream))
                        {
                            outputString = reader.ReadToEnd();
                        }
                        return outputString;
                    }
                }
            }
        }
        private static byte[] HexToBin(String hexString)
        {

            int charCount = hexString.Length;
            byte[] output = new byte[charCount / 2];
            for (int i = 0; i < charCount; i += 2)
            {
                output[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
            }

            return output;
        }
        private static String getSSN(String cipher)
        {
            int delimiterIndex = cipher.IndexOf(":");
            String SSN = cipher.Substring(0, delimiterIndex);
            return SSN;
        }

        private static String getIV(String cipher)
        {
            int delimiterIndex = cipher.IndexOf(":");
            String IV = cipher.Substring(delimiterIndex + 1);
            return IV;
        }


        // Reference: https://stackoverflow.com/questions/311165/how-do-you-convert-a-byte-array-to-a-hexadecimal-string-and-vice-versa
        private static string ByteArrayToString(byte[] ba)
        {
            string hex = BitConverter.ToString(ba);
            return hex.Replace("-", "");
        }
    }
}

第73行(遇到异常)是解密方法中使用块的使用块的末端:

    using (StreamReader reader = new StreamReader(cryptStream))
                    {
                        outputString = reader.ReadToEnd();
                    }

我提到了以下问题,但无法解决我的问题。

最初,数据是在PHP应用程序中加密的,并使用C#应用程序进行解密(上面使用上面几乎完全相同的解密方法)。现在,我想使用C#加密和解密数据。但是,我仍然必须能够正确解密现有数据(使用PHP进行了加密),因此我宁愿不太修改解密方法太多。

任何建议都将不胜感激。

您在这里有小错误:

ICryptoTransform myDecrypter = myAes.CreateDecryptor(myAes.Key, myAes.IV);
using (MemoryStream memory = new MemoryStream(ivBytes))

您将IV值传递给解密,而不是实际加密的字节。修复:

ICryptoTransform myDecrypter = myAes.CreateDecryptor(myAes.Key, myAes.IV);
using (MemoryStream memory = new MemoryStream(valBytes))

最新更新