我有一个小应用程序,它可以读取任何文件(即 .exe、.jpg、.img 和所有其他文件),将其传输到bytes[]
trough File.ReadAllBytes()
,使用 3DES 加密并使用File.WriteAllBytes()
. 比有做同样反向的解密方法。我的问题是,在 300MB 的原始文件中一切正常,而不是内存不足异常。任何建议如何解决这个问题?如何处理大于 1GB 的文件?它可以帮助使用streamreader或cryptostream reader和writer吗?
读取和加密文件:
try
{
saveFileDialog1.FileName = "";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
fileToEncrypt = File.ReadAllBytes(openFileDialog1.FileName);
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(textBox1.Text));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock(fileToEncrypt, 0, fileToEncrypt.Length);
saveFileDialog1.FileName = openFileDialog1.SafeFileName;
saveFileDialog1.ShowDialog();
if (saveFileDialog1.FileName != "")
{
File.WriteAllBytes(saveFileDialog1.FileName, Results);
}
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
catch
{
MessageBox.Show("Your system has not enough memory.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
解密和保存:
try
{
openFileDialog1.FileName = "";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
fileToDecrypt = File.ReadAllBytes(openFileDialog1.FileName);
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(textBox1.Text));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(fileToDecrypt, 0, fileToDecrypt.Length);
saveFileDialog1.FileName = Path.GetFileName(openFileDialog1.FileName);
saveFileDialog1.ShowDialog();
if (saveFileDialog1.FileName != "")
{
File.WriteAllBytes(saveFileDialog1.FileName, Results);
}
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
catch
{
MessageBox.Show("Master password is wrong", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
我只是业余爱好编码器,所以我祈祷我的代码有一些仁慈:)
textbox1.Text
是主密码。