【发布时间】:2015-07-14 12:21:28
【问题描述】:
我决定在 C# 中使用 SharpAESCrypt 实现 AES 加密。根据他们的文档 (https://www.aescrypt.com/sharp_aes_crypt.html),您应该能够使用静态方法,提供密码字符串、纯文本输入流和输出流。我从输出流中得到的数据似乎全为零。
我怀疑我在将字符串转换为流并返回时做错了。任何人都可以看到下面的代码明显有什么问题吗? (它可以编译运行,但是newByteArray末尾是0)
private void encryptMemStream()
{
byte[] byteArray = Encoding.UTF8.GetBytes(DecryptedTB.Text);
using (MemoryStream plainText = new MemoryStream(byteArray))
{
using (MemoryStream encryptedData = new MemoryStream())
{
//plainText.Write(byteArray, 0, byteArray.Length);
SharpAESCrypt.Encrypt(PasswordTB.Text, plainText, encryptedData);
encryptedData.Position = 0;
byte[] newByteArray = new byte[encryptedData.Length];
newByteArray = encryptedData.ToArray();
EncryptedTB.Text = Encoding.UTF8.GetString(newByteArray);
}
}
}
编辑:此代码的本机实现使用 fileStreams,但它也应该与 MemoryStreams 一起使用。我将测试文件流并在此处添加我的结果。
更多编辑:
因此,当您使用文件流时,您会调用此代码
//Code from the AES Crypt Library
public static void Encrypt(string password, string inputfile, string outputfile)
{
using (FileStream infs = File.OpenRead(inputfile))
using (FileStream outfs = File.Create(outputfile))
Encrypt(password, infs, outfs);
}
调用我一直直接调用的函数
//Code from the AES Crypt Library
public static void Encrypt(string password, Stream input, Stream output)
{
int a;
byte[] buffer = new byte[1024 * 4];
SharpAESCrypt c = new SharpAESCrypt(password, output, OperationMode.Encrypt);
while ((a = input.Read(buffer, 0, buffer.Length)) != 0)
c.Write(buffer, 0, a);
c.FlushFinalBlock();
}
使用 MemoryStream 和 FileStream 显然存在一些我不理解的细微差别。 FileStream 工作正常,其中 MemoryStream 返回一个空白数组...
【问题讨论】:
-
使用流时应该使用using
-
您能详细说明一下吗?
-
我会避免使用 ascii。
-
我会尝试其他编码类型。
-
这并没有解决问题。