我正在尝试对内存流进行解密算法,但是我遇到的问题是,解密后生成的内存流始终为空
这是我的代码:
private MemoryStream Encrypt()
{
byte[] toEncrypt = new byte[] { 1, 2, 3, 4, 5, 6 };
int keySize = 256;
int blockSize = 128;
byte[] passwordBytes = generateRandomBytes();
byte[] ivBytes = new byte[blockSize / 8];
Buffer.BlockCopy(passwordBytes, 0, ivBytes, 0, ivBytes.Length);
MemoryStream fsOut = new MemoryStream();
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.BlockSize = blockSize;
AES.KeySize = keySize;
AES.Mode = CipherMode.CFB;
AES.FeedbackSize = 8;
AES.Padding = PaddingMode.None;
AES.Key = passwordBytes;
AES.IV = ivBytes;
using (var encryptor = AES.CreateEncryptor())
using (var cs = new CryptoStream(new MemoryStream(toEncrypt, 0, toEncrypt.Length), encryptor, CryptoStreamMode.Read))
{
cs.CopyTo(fsOut);
}
}
return fsOut;
}
private MemoryStream FileDecrypt(MemoryStream memStream)
{
int keySize = 256;
int blockSize = 128;
byte[] passwordBytes = generateRandomBytes();
byte[] ivBytes = new byte[blockSize / 8];
Buffer.BlockCopy(passwordBytes, 0, ivBytes, 0, ivBytes.Length);
MemoryStream fsOut = new MemoryStream();
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.BlockSize = blockSize;
AES.KeySize = keySize;
AES.Mode = CipherMode.CFB;
AES.FeedbackSize = 8;
AES.Padding = PaddingMode.None;
AES.Key = passwordBytes;
AES.IV = ivBytes;
using (var decryptor = AES.CreateDecryptor())
using (var cs = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read))
{
cs.CopyTo(fsOut);
}
}
/*
RijndaelManaged AES = new RijndaelManaged();
AES.KeySize = keySize;
AES.BlockSize = blockSize;
AES.Key = passwordBytes;
AES.IV = ivBytes;
AES.Padding = PaddingMode.None;
AES.Mode = CipherMode.CFB;
AES.FeedbackSize = 8;
CryptoStream cs = new CryptoStream(memStream, AES.CreateDecryptor(), CryptoStreamMode.Read);
MemoryStream fsOut = new MemoryStream();
try
{
cs.CopyTo(fsOut);
}
catch (CryptographicException ex_CryptographicException)
{
Console.WriteLine("CryptographicException error: " + ex_CryptographicException.Message);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
try
{
cs.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error by closing streams: " + ex.Message);
}
*/
return fsOut;
}
MemoryStream encrypted = Encrypt();
MemoryStream decrypted = FileDecrypt(encrypted);
Console.WriteLine("Decrypted: ", bytesToString(decrypted.GetBuffer()));
由于真正的问题在于从tcp连接接收到的文件创建的内存流,因此我尝试对阵列(1,2,3,4,5,6)进行测试加密。最后,我还要打印(1,2,3,4,5,6)。但是最后它只显示“ Decrypted:”,并且我没有收到任何错误或异常,执行过程很顺利。我在做什么错了?