加速我的应用程序
本文关键字:应用程序 我的 加速 | 更新日期: 2023-09-27 18:37:18
我正在使用高级加密标准算法创建一个文件加密应用程序,但我发现我的应用程序非常慢,尤其是当我加密大量数据时,例如 80MB 的文件大小,30 分钟。已经过去了,但我的应用程序尚未完成加密大小为 80MB 的文件。
我在加密算法中使用ECB(电子密码本)模式
如何加快应用程序加密大量数据的速度?我做了一些研究,我发现这个,http://en.wikipedia.org/wiki/Speedup,但我不确定这是否是我问题的答案......或者如果我使用后台工作者是否有效?顺便说一下,我在项目开发中使用Visual Studio 2008。
这是我加密文件的代码。
private void cmdEncrypt_Click(object sender, EventArgs e)
{
AESECB aes = new AESECB();
FileInfo fInfo = new FileInfo(txtFileSource.Text);
if (txtFileSource.Text == "")
{
MessageBox.Show("Please Select a File", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
if (txtSecretKey.Text == "")
{
MessageBox.Show("Please Enter the password", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
if (fInfo.Exists == false)
{
MessageBox.Show("File Not Found!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
byte[] bytePadding = aes.filePadding(txtFileSource.Text);
byte[] fByte = aes.getFileByte(txtFileSource.Text);
int farrLength = (bytePadding.Length + fByte.Length);
byte[] newFbyte = new byte[farrLength];
byte[] encryptedFByte = new byte[farrLength];
int counterBytePadding =0;
byte firstByte = 0;
for (int i = 0; i < farrLength; i++)
{
if (i < fByte.Length)
{
newFbyte[i] = fByte[i];
}
else
{
newFbyte[i] = bytePadding[counterBytePadding];
counterBytePadding++;
}
}
int plainFileBlock = newFbyte.Length / 16;
progressBar1.Maximum = plainFileBlock-1;
progressBar1.Visible = true;
int counter = 0;
int counter2 = 0;
for (int j = 0; j < plainFileBlock; j++)
{
byte[] encfbyte = aes.fileEncrypt(txtSecretKey.Text, newFbyte, counter);
for (int k = 0; k < 16; k++)
{
encryptedFByte[counter2] = encfbyte[k];
counter2++;
}
progressBar1.Value = j;
counter = counter + 16;
}
progressBar1.Visible = false;
int bytesToRead = encryptedFByte.Length;
string newPath = txtFileSource.Text + ".aesenc";
using (FileStream newFile = new FileStream(newPath, FileMode.Create, FileAccess.Write))
{
newFile.Write(encryptedFByte, 0, bytesToRead);
}
MessageBox.Show("Encryption Done!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
"对你的代码充满信心"是很好的,但所有优秀的程序员都会衡量。
这很简单,这样做:
using System.Diagnostics;
var startTime = DateTime.Now;
//some code here
Debug.WriteLine("This took {0}", DateTime.Now.Subtract(startTime));
然后在VS(视图>输出)中查看输出窗口。
通过用这两行包装方法的不同部分,您将识别慢速位。
我的怀疑是你逐字节复制 80MB 的循环。尝试Array.Resize
这里.
正如Weston所建议的那样,请测量您的代码以识别缓慢的内容。也就是说,可能是循环的文件加密减慢了您的速度。如果是这样,您绝对可以通过使用超过 1 个 CPU 来加快该过程。查找 C# 中的并行构造:"Parallel.For"。
下面是一个简单的示例:http://www.dotnetcurry.com/ShowArticle.aspx?ID=608