0

我正在尝试使用AesCryptoServiceProvider来实现与Aes. 这是我的AesCryptoServiceProvider版本:

        public string version1(string plainText, string encryptionKey, string initializationVector)
        {
            AesCryptoServiceProvider provider = new AesCryptoServiceProvider
            {
                BlockSize = 128,
                Padding = PaddingMode.PKCS7,
                Key = Convert.FromBase64String(encryptionKey),
                IV = Encoding.UTF8.GetBytes(initializationVector)
            };

            byte[] buffer = Encoding.ASCII.GetBytes(plainText);
            byte[] encrypted = provider.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length);
            return Convert.ToBase64String(encrypted);
        }

这是Aes它的版本:

        public string version2(string plainText, string encryptionKey, string initializationVector)
        {
            byte[] clearBytes = Encoding.UTF8.GetBytes(plainText);
            byte[] encryptedBytes;
            byte[] iv = Encoding.UTF8.GetBytes(initializationVector);

            using (Aes aes = Aes.Create())
            {
                aes.BlockSize = 128;
                aes.Padding = PaddingMode.PKCS7;
                aes.Key = Convert.FromBase64String(encryptionKey);
                aes.IV = iv;

                using (MemoryStream ms = new MemoryStream())
                using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                    encryptedBytes = ms.ToArray();
                }
            }

            byte[] ivEncryptedBytes = new byte[iv.Length + encryptedBytes.Length];
            Buffer.BlockCopy(iv, 0, ivEncryptedBytes, 0, iv.Length);
            Buffer.BlockCopy(encryptedBytes, 0, ivEncryptedBytes, iv.Length, encryptedBytes.Length);

            return Convert.ToBase64String(ivEncryptedBytes);
        }

当我使用 version1 和 version2 加密相同的字符串时,它们就不同了。关于这两种方法有何不同以及如何使 version1 产生与 version2 相同的加密字符串的任何想法?(ps我对加密很陌生,如果答案很明显,我很抱歉)谢谢!

4

1 回答 1

0

正如@MichaelFehr 指出的那样,在将字节转换回字符串之前,版本2 仅将初始化向量和加密字节连接在一起。我已经测试过,如果我在version1中以与version2相同的方式连接字符串,结果字符串将变得相同。

于 2020-06-10T14:25:32.833 回答