Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

C#AES解密 输入参数为32Byte的字节数组IV和16byte的字节数组密文

  1. User

    C#AES解密 输入参数为32Byte的字节数组IV和16byte的字节数组密文

  2. Assistant

    下面是使用C#解密AES加密的示例代码:

    using System;
    using System.Security.Cryptography;
    using System.Text;
    
    public class Program
    {
        public static void Main(string[] args)
        {
            // 输入参数
            byte[] iv = new byte[32];
            byte[] encryptedBytes = new byte[16];
    
            // 使用相应的值初始化iv和encryptedBytes
    
            // 密钥
            byte[] keyBytes = Encoding.UTF8.GetBytes("your key");
    
            byte[] decryptedBytes = DecryptAES(encryptedBytes, keyBytes, iv);
            string decryptedText = Encoding.UTF8.GetString(decryptedBytes);
    
            Console.WriteLine(decryptedText);
        }
    
        public static byte[] DecryptAES(byte[] encryptedBytes, byte[] keyBytes, byte[] iv)
        {
            using (Aes aes = Aes.Create())
            {
                aes.KeySize = 128;
                aes.BlockSize = 128;
                aes.Key = keyBytes;
                aes.IV = iv;
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;
    
                using (ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
                {
                    return PerformCryptography(encryptedBytes, decryptor);
                }
            }
        }
    
        private static byte[] PerformCryptography(byte[] inputBytes, ICryptoTransform transform)
        {
            using (var outputStream = new MemoryStream())
            {
                using (var cryptoStream = new CryptoStream(outputStream, transform, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(inputBytes, 0, inputBytes.Length);
                    cryptoStream.FlushFinalBlock();
                    return outputStream.ToArray();
                }
            }
        }
    }
    

    在上面的示例代码中,使用DecryptAES方法对密文进行解密。请将your key替换为正确的密钥。解密后的结果以字节数组的形式返回,并可以通过Encoding.UTF8.GetString方法将其转换为字符串。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.