【发布时间】:2015-03-11 14:40:20
【问题描述】:
因此,我在 C# 加密/解密算法中实现了该算法,该算法在加密/解密任何文件时都可以正常工作。 我现在的问题是,我怎样才能只加密(然后解密)文件的前几个(兆)字节。
例如:我有一个 2GB 的文件,我只想加密这个文件的 3MB。
我已经尝试了一些东西,但没有达到我想要的效果。我试图计算读取的字节数,如果读取的字节超过限制(3MB),则停止加密并继续将正常(未加密的数据)写入文件。但解密后,出现“填充”异常等。另一个例子:我(用这种方法)“成功”加密了一个50kb的.txt文件的20kb,但解密后,.txt文件的最后一行还有一些“奇怪的“字符 - 所以这不起作用(如果我想要例如加密图像 - 在解密后仍然“损坏”)。
对于加密我使用这个函数:
public static bool Encrypt(string inputFilePath, string outputfilePath, string EncryptionKey)
{
try
{
using (FileStream fsInput = new FileStream(inputFilePath, FileMode.Open))
{
using (FileStream fsOutput = new FileStream(outputfilePath, FileMode.Create))
{
fsInput.Position = 0;
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (CryptoStream cs = new CryptoStream(fsOutput, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int bytesRead;
int byteWriteCounter = 0;
do
{
bytesRead = fsInput.Read(buffer, 0, bufferLen);
//my method
if(byteWriteCounter <= 20000){ //if readed bytes <= 20kb
cs.Write(buffer, 0, bytesRead); // then encrypt
}else{ // if bytes are over 20kb
fsOutput.Write(buffer, 0, bytesRead); //write normal (unecrypted)
}
byteWriteCounter += bytesRead;
} while (bytesRead != 0);
return true;
}
}
}
}
}
catch (SystemException se)
{
Console.WriteLine(se);
return false;
}
}
对于解密(我用的)是类似的功能/方法:
public static bool Decrypt(string inputFilePath, string outputfilePath, string EncryptionKey)
{
try
{
using (FileStream fsInput = new FileStream(inputFilePath, FileMode.Open))
{
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (FileStream fsOutput = new FileStream(outputfilePath, FileMode.Create))
{
using (CryptoStream cs = new CryptoStream(fsOutput, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int bytesRead;
int byteWriteCounter = 0;
do
{
bytesRead = fsInput.Read(buffer, 0, bufferLen);
//my method
if(byteWriteCounter <= 20000){ //if readed bytes <= 20kb
cs.Write(buffer, 0, bytesRead); // then decrypt
}else{ // if bytes are over 20kb
fsOutput.Write(buffer, 0, bytesRead); //write normal data
}
byteWriteCounter += bytesRead;
} while (bytesRead != 0);
}
}
}
}
return true;
}
catch (SystemException s)
{
Console.WriteLine(s);
return false;
}
}
【问题讨论】:
-
顺便说一句,20000 字节!= 20 kb。
-
嗯.. 我想每个人都会明白我的意思。在这个代码示例中,如您所见,我在任何地方都不需要完全相等。
标签: c# encryption cryptography byte