我有一种加密方法,运行速度非常慢。加密几百MB的数据需要大约20分钟时间。我不确定我的方法是否正确。如果您能提供帮助、想法或建议,将不胜感激。
private void AES_Encrypt(string inputFile, string outputFile, byte[] passwordBytes, byte[] saltBytes)
{
FileStream fsCrypt = new FileStream(outputFile, FileMode.Create);
RijndaelManaged AES = new RijndaelManaged();
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Padding = PaddingMode.Zeros;
AES.Mode = CipherMode.CBC;
CryptoStream cs = new CryptoStream(fsCrypt,
AES.CreateEncryptor(),
CryptoStreamMode.Write);
FileStream fsIn = new FileStream(inputFile, FileMode.Open);
int data;
while ((data = fsIn.ReadByte()) != -1)
cs.WriteByte((byte)data);
fsCrypt.Flush();
cs.Flush();
fsIn.Flush();
fsIn.Close();
cs.Close();
fsCrypt.Close();
}
感谢您提供的帮助!
FileStream
中使用ReadAllBytes
方法读取所有字节,然后将结果缓冲区通过Write
方法写入到CryptoStream
中。 - Jonathon Chase