C# 实现AES/CBC/PKCS5解密

对字符串进行解密

public static string Encrypt(string toEncrypt, string key, string iv)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
            byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv);
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.IV = ivArray;
            rDel.Mode = CipherMode.CBC;
            rDel.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = rDel.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

以流的形式对字符串进行解密:

    public static void DecryptStream(string combinePath,string private_key,string savePath, string iv) {
        Rijndael crypt = Rijndael.Create();
        crypt.Key = UTF8Encoding.UTF8.GetBytes(private_key);
        crypt.IV = UTF8Encoding.UTF8.GetBytes(iv);
        crypt.Mode = CipherMode.CBC;
        crypt.Padding = PaddingMode.PKCS7;

        Stream inputStream = new FileStream(@combinePath,FileMode.Open);
        Stream outputStream = new FileStream(@savePath, FileMode.OpenOrCreate);

        byte[] initializationVectorLength = new byte[sizeof(int)];
        CryptoStream cryptostream = new CryptoStream(inputStream, crypt.CreateDecryptor(), CryptoStreamMode.Read);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = cryptostream.Read(buffer, 0, buffer.Length)) > 0)
        {
            outputStream.Write(buffer, 0, len);
        }
        outputStream.Flush();
        cryptostream.Close();
        inputStream.Close();
    }

你可能感兴趣的:(C# 实现AES/CBC/PKCS5解密)