我找到了此代码,并在VS 2017 C#中使用它来加密和解密文件。如果我加密.txt文件,则解密该文件并将解密后的输出与原始文件进行比较,然后匹配。如果我尝试使用.bin文件,则该文件不匹配,我也不知道为什么。我认为它应该适用于任何类型的文件? 有人可以看到问题所在吗?
static void AESEncryptCBC(string plainText, Stream encryptedOutput, byte[] key)
{
if (plainText == null || plainText == string.Empty)
return;
if (key == null | key.Length == 0)
return;
if (encryptedOutput == null)
return;
using (var aes = new AesManaged())
{
aes.Key = key;
var salt = new byte[16];
using (var rngCSP = new RNGCryptoServiceProvider())
{
rngCSP.GetBytes(salt);
}
aes.IV = salt;
using (var encryptor = aes.CreateEncryptor())
{
encryptedOutput.Write(salt, 0, salt.Length);//write the salt to the begining of the stream
using (var cs = new CryptoStream(encryptedOutput, encryptor, CryptoStreamMode.Write))
{
using (var writer = new StreamWriter(cs))
{
writer.Write(plainText);
}
}
}
}
}
static void AESEncryptECB(string plainText, Stream encryptedOutput, byte[] key)
{
if (plainText == null || plainText == string.Empty)
return;
if (key == null | key.Length == 0)
return;
if (encryptedOutput == null)
return;
using (var aes = new AesManaged())
{
aes.Key = key;
aes.Mode = CipherMode.ECB;
var salt = new byte[16];
using (var rngCSP = new RNGCryptoServiceProvider())
{
rngCSP.GetBytes(salt);
}
aes.IV = salt;
using (var encryptor = aes.CreateEncryptor())
{
encryptedOutput.Write(salt, 0, salt.Length); //write the salt to the begining of the stream
using (var cs = new CryptoStream(encryptedOutput, encryptor, CryptoStreamMode.Write))
{
using (var writer = new StreamWriter(cs))
{
writer.Write(plainText);
}
}
}
}
}
static string AESDecryptECB(Stream encryptedInput, byte[] key)
{
if (encryptedInput == null || encryptedInput.Length == 0)
return null;
if (key == null || key.Length == 0)
return null;
var salt = new byte[16];
encryptedInput.Read(salt, 0, salt.Length);
using (var aes = new AesManaged())
{
aes.Key = key;
aes.IV = salt;
aes.Mode = CipherMode.ECB;
using (var decryptor = aes.CreateDecryptor())
{
using (var cs = new CryptoStream(encryptedInput, decryptor, CryptoStreamMode.Read))
{
using (var reader = new StreamReader(cs))
{
return reader.ReadToEnd();
}
}
}
}
}
static string AESDecryptCBC(Stream encryptedInput, byte[] key)
{
if (encryptedInput == null || encryptedInput.Length == 0)
return null;
if (key == null || key.Length == 0)
return null;
var salt = new byte[16];
encryptedInput.Read(salt, 0, salt.Length);
using (var aes = new AesManaged())
{
aes.Key = key;
aes.IV = salt;
using (var decryptor = aes.CreateDecryptor())
{
using (var cs = new CryptoStream(encryptedInput, decryptor, CryptoStreamMode.Read))
{
using (var reader = new StreamReader(cs))
{
return reader.ReadToEnd();
}
}
}
}
}
答案 0 :(得分:5)
简而言之,您的问题是由于您无法将任意二进制数据表示为字符串这一事实引起的。
StreamWriter
和StreamReader
类可处理文本。二进制数据不是文本。没有字符编码的概念。您应该在此级别上使用byte[]
,而不是字符串!尝试从您的代码中删除StreamWriter/Reader
。