我正在尝试使用 RijndaelManaged 通过套接字加密和解密文件流,但我一直遇到异常
CryptographicException:要解密的数据长度无效。 在 System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(字节 [] inputBuffer,Int32 inputOffset,Int32 inputCount) 在 System.Security.Cryptography.CryptoStream.FlushFinalBlock() 在 System.Security.Cryptography.CryptoStream.Dispose(布尔处理)
当整个文件已被传输时,在 receiveFile 中的 using 语句结束时会引发异常。
我尝试在网上搜索,但只找到了在加密和解密单个字符串时使用 Encoding 时出现的问题的答案。我使用 FileStream,所以我没有指定要使用的任何编码,所以这不应该是问题。这些是我的方法:
private void transferFile(FileInfo file, long position, long readBytes)
{
// transfer on socket stream
Stream stream = new FileStream(file.FullName, FileMode.Open);
if (position > 0)
{
stream.Seek(position, SeekOrigin.Begin);
}
// if this should be encrypted, wrap the encryptor stream
if (UseCipher)
{
stream = new CryptoStream(stream, streamEncryptor, CryptoStreamMode.Read);
}
using (stream)
{
int read;
byte[] array = new byte[8096];
while ((read = stream.Read(array, 0, array.Length)) > 0)
{
streamSocket.Send(array, 0, read, SocketFlags.None);
position += read;
}
}
}
private void receiveFile(FileInfo transferFile)
{
byte[] array = new byte[8096];
// receive file
Stream stream = new FileStream(transferFile.FullName, FileMode.Append);
if (UseCipher)
{
stream = new CryptoStream(stream, streamDecryptor, CryptoStreamMode.Write);
}
using (stream)
{
long position = new FileInfo(transferFile.Path).Length;
while (position < transferFile.Length)
{
int maxRead = Math.Min(array.Length, (int)(transferFile.Length - position));
int read = position < array.Length
? streamSocket.Receive(array, maxRead, SocketFlags.None)
: streamSocket.Receive(array, SocketFlags.None);
stream.Write(array, 0, read);
position += read;
}
}
}
这是我用来设置密码的方法。byte[] init 是一个生成的字节数组。
private void setupStreamCipher(byte[] init)
{
RijndaelManaged cipher = new RijndaelManaged();
cipher.KeySize = cipher.BlockSize = 256; // bit size
cipher.Mode = CipherMode.ECB;
cipher.Padding = PaddingMode.ISO10126;
byte[] keyBytes = new byte[32];
byte[] ivBytes = new byte[32];
Array.Copy(init, keyBytes, 32);
Array.Copy(init, 32, ivBytes, 0, 32);
streamEncryptor = cipher.CreateEncryptor(keyBytes, ivBytes);
streamDecryptor = cipher.CreateDecryptor(keyBytes, ivBytes);
}
有人知道我可能做错了什么吗?