我有几个大的加密文件,使用的代码来自
https://gist.github.com/hanswolff/8809275
.
这是加密代码:
BUF_LENGTH = 16
FileStream FsInput = new FileStream(InFileName, FileMode.Open, FileAccess.Read);
FileStream FsOutput = new FileStream(OutFileName, FileMode.OpenOrCreate, FileAccess.Write);
byte[] ReadBuffer = new byte[BUF_LENGTH];
long InFileLength = FsInput.Length;
long AllBytes = 0;
int PartBytes = 0;
if (InFileLength == 0)
return false;
ICryptoTransform AESEncryptor = AESEncoder.CreateEncryptor(KeyBytes, null);
CrStream = new CryptoStream(FsOutput, AESEncryptor, CryptoStreamMode.Write);
while (AllBytes < InFileLength)
{
PartBytes = FsInput.Read(ReadBuffer, 0, BUF_LENGTH);
CrStream.Write(ReadBuffer, 0, PartBytes);
AllBytes = AllBytes + PartBytes;
}
CrStream.Close();
FsInput.Close();
FsOutput.Flush();
FsOutput.Close();
对于完整的文件,代码可以很好地工作。
我们想要的是有选择地寻找加密文件的特定块,并仅解密该块。
我猜这是可能的?
CipherInputStream
似乎能完成任务,但我需要用C#完成。
private byte[] read_block(String filepath, long pos, int length)
{
byte[] data = readfile(filepath, pos, length); // returns the specific block.
byte[] plaindata = new byte[data.Length];
byte[] kb = PrepareKeyIvBytes();
byte[] nba = new byte[IvBytes.Length];
IvBytes.CopyTo(nba, 0);
AESDecoder = new Aes128CounterMode(nba);
ICryptoTransform AESDecryptor = AESDecoder.CreateDecryptor(IvBytes, null);
MemoryStream ms = new MemoryStream();
CrStream = new CryptoStream(ms, AESDecryptor, CryptoStreamMode.Write);
CrStream.Write(data, 0, length);
CrStream.Close();
ms.Flush();
ms.ToArray().CopyTo(plaindata, 0);
return plaindata;
}
我写了这段代码,但它只在我们保持
pos
变量设置为0。如果我把它设置为其他值,比如512,它就不起作用了。
有人知道我该去哪里吗?
谢谢