解密返回x00流

时间:2013-12-25 02:31:01

标签: c# encryption stream null

我遇到了使用CryptoStream解密到MemoryStream的问题。当我解密从字符串转换为byte []的数据时,它正常解密,但是当我将图像数据传递给解密器时,它返回x00填充的流,其长度与图像数据相同。顺便说一下,没有例外。

private SymmetricAlgorithm crypto;

...

public byte[] Encrypt(byte[] Stream)
    {
        ICryptoTransform encryptor = crypto.CreateEncryptor();
        // Create the streams used for encryption. 
        using (MemoryStream msEncrypt = new MemoryStream())
        {
            using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            {
                int written = 0;
                int length = Stream.Length;
                int blockSize = crypto.BlockSize / 8;
                while (written < length)
                {
                    int toWrite = Math.Min(blockSize, length - written);
                    if ((length - written) > blockSize)
                    {
                        csEncrypt.Write(Stream, written, blockSize);
                        written += blockSize;
                        csEncrypt.Flush();
                    }
                    else
                    {
                        csEncrypt.Write(Stream, written, toWrite);
                        written += toWrite;
                        csEncrypt.FlushFinalBlock();
                    }
                }
                resBytes = msEncrypt.ToArray();
            }
        }
        return resBytes;
    }

...

public byte[] Decrypt(byte[] Stream)
    {
        ICryptoTransform decryptor = crypto.CreateDecryptor();
        MemoryStream decrypted = new MemoryStream();

        using (MemoryStream msDecrypt = new MemoryStream(Stream))
        {
            using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
            {
            csDecrypt.CopyTo(decrypted, crypto.BlockSize);
            resBytes = decrypted.ToArray();                    
            decrypted.Dispose();

            resBytes = decrypted.ToArray();
            return resBytes;
            }
        }
    }

0 个答案:

没有答案