首页 > 解决方案 > 解密 AES 加密文件的选择性部分

问题描述

我有一些使用来自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,它就不起作用。
有人知道我应该去哪里看吗?
谢谢!

标签: c#.netencryptioncryptographyaes

解决方案


推荐阅读