C# 如何在c中解密后获得字节作为输出#

C# 如何在c中解密后获得字节作为输出#,c#,C#,在C#中解密字节数组后,我需要字节数组作为输出。我正在使用下面的代码。但我得到了“填充错误”。下面的方法是否正确,或者我需要进行任何更改 static byte[] DecryptBytesToBytes(byte[] cipherText, byte[] Key, byte[] IV) { // Check arguments. if (cipherText == null || cipherText.Length <= 0) throw new A

在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;
}
静态字节[]解密ByTestObytes(字节[]密文,字节[]密钥,字节[]IV)
{
//检查参数。

if(cipherText==null | | cipherText.Length如果你想获取字节,为什么要使用
StreamReader
?这对我来说似乎是一个非常糟糕的主意。可能是@jonsket的重复。你能指定任何其他方法或代码吗?我可能会创建一个新的MemoryStream并调用
csDecrypt.CopyTo(目标)
然后返回
target.ToByteArray()
…但如果问题是它无法解密您的数据,那就没用了。如果您试图获取字节,为什么要使用
StreamReader
?这对我来说似乎是一个非常糟糕的主意。@jonsket的可能副本您能指定任何其他方法或代码吗?我可能会创建一个新的MemoryStream并调用它
csDecrypt.CopyTo(target)
然后返回
target.ToByteArray()
…但是如果问题是它无法解密您的数据,那就没有帮助了。