如何在c#中解密后将字节作为输出

时间:2016-04-21 05:49:09

标签: c#

在C#中解密字节数组后,我需要字节数组作为输出。我正在使用下面的代码。但我得到“填充错误”。以下方法是否正确或我需要进行任何更改。

  static byte[] DecryptBytesToBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
    // Check arguments. 
    if (cipherText == null || cipherText.Length <= 0)
        throw new ArgumentNullException("cipherText");
    if (Key == null || Key.Length <= 0)
        throw new ArgumentNullException("Key");
    if (IV == null || IV.Length <= 0)
        throw new ArgumentNullException("Key");
    // Declare the string used to hold 
    // the decrypted text.
    byte[] encrypted = null;
    // Create an AesCryptoServiceProvider object 
    // with the specified key and IV. 
    using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
    {
        //aesAlg.Key = Key;
        //aesAlg.IV = IV;
        aesAlg.KeySize = 128;
        aesAlg.BlockSize = 128;
        aesAlg.Key = Key;
        aesAlg.IV = Key;
        aesAlg.Mode = CipherMode.CBC;
        aesAlg.Padding = PaddingMode.PKCS7;
        // Create a decrytor to perform the stream transform.
        ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
        // Create the streams used for decryption. 
        using (MemoryStream msDecrypt = new MemoryStream(cipherText))
        {
            using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
            {
                using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                {
                    string encrypted_text = srDecrypt.ReadToEnd();
                    encrypted = new byte[encrypted_text.Length * sizeof(char)];
                    System.Buffer.BlockCopy(encrypted_text.ToCharArray(), 0, encrypted, 0, encrypted.Length);
                }
            }
        }
    }
    return encrypted;
}

0 个答案:

没有答案