通过对称解密算法AES-256-CBC对文件进行加密解密

以下例子使用对称解密使用的算法为 AES-256-CBC(256位密钥 = 32 bytes Key,通过SHA256计算得到,128位iv=16 bytes IV,通过MD5计算得到),数据采用PKCS#7填充。

	using System.Security.Cryptography;
	using System.Text;
	
    public static void Main()
    {
        // 定义加密密钥和初始化向量
        byte[] key = new byte[32]; // 256位密钥
        byte[] iv = new byte[16]; // 128位IV
        key= SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes("密钥"));
        iv = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("向量"));

        // 也可生成随机密钥和向量
        //using (var aes = Aes.Create())
        //{
        //    key = aes.Key;
        //    iv = aes.IV;
        //}
        
        // 创建加密器和解密器对象
        using (var aes =  Aes.Create())
        {
            aes.KeySize = 256;
            aes.Key = key;
            aes.IV = iv;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;

            // 加密文件数据流
            using (var inputStream = new FileStream(@"inputfile.txt", FileMode.Open))
            using (var outputStream = new FileStream(@"encryptedOutputFile", FileMode.Create))
            using (var encryptor = aes.CreateEncryptor())
            using (var cryptoStream = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write))
            {
                inputStream.CopyTo(cryptoStream);
            }

            // 解密文件数据流
            using (var inputStream = new FileStream(@"encryptedOutputFile", FileMode.Open))
            using (var outputStream = new FileStream(@"decryptedOutputFile.txt", FileMode.Create))
            using (var decryptor = aes.CreateDecryptor())
            using (var cryptoStream = new CryptoStream(inputStream, decryptor, CryptoStreamMode.Read))
            {
                cryptoStream.CopyTo(outputStream);
            }
        }
    }

你可能感兴趣的:(.NET,.netcore,文件加密,AES,CBC)