我找到了这段代码并在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();
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
简而言之,您的问题是由于您无法将任意二进制数据表示为字符串.
该StreamWriter
和StreamReader
文字类工作.二进制数据不是文本.没有字符编码的概念.你应该byte[]
在这个级别上工作,而不是字符串!尝试StreamWriter/Reader
从代码中消除.
归档时间: |
|
查看次数: |
75 次 |
最近记录: |