3

我想使用 CryptoStream 将数据附加到已经加密的文件(AES、CBC 模式、填充 PKCS#7)而不读取和写入整个文件。

例子:

旧内容:"Hello world..."

新内容:"Hello world, with appended text"

当然,我必须读取单个数据块,然后将其附加到已经存在的块中。在上面提到的示例中,我必须读取第一个块中存在的字节数(14 个字节)并将两个字节附加到第一个块,然后写入其余的附加文本

"Hello world, wi"
"th appended text"

我面临的一个问题是我无法读取数据块中的字节数。有没有办法找出存在的字节数(在示例中为 14)?

此外,我被卡住了,因为 CryptoStreamMode 只有读写成员,但没有更新。

有没有办法使用 CryptoStream 完成我想要的功能?

4

1 回答 1

7

它有点复杂,但不是太多。请注意,这是针对 CBC 模式 + PKCS#7!

三种方法:WriteStringToFile将创建一个新文件,AppendStringToFile将附加到已加密的文件(就像WriteStringToFile文件丢失/空一样),ReadStringFromFile将从文件中读取。

public static void WriteStringToFile(string fileName, string plainText, byte[] key, byte[] iv)
{
    using (Rijndael algo = Rijndael.Create())
    {
        algo.Key = key;
        algo.IV = iv;
        algo.Mode = CipherMode.CBC;
        algo.Padding = PaddingMode.PKCS7;

        // Create the streams used for encryption.
        using (FileStream file = new FileStream(fileName, FileMode.Create, FileAccess.Write))
        // Create an encryptor to perform the stream transform.
        using (ICryptoTransform encryptor = algo.CreateEncryptor())
        using (CryptoStream cs = new CryptoStream(file, encryptor, CryptoStreamMode.Write))
        using (StreamWriter sw = new StreamWriter(cs))
        {
            // Write all data to the stream.
            sw.Write(plainText);
        }
    }
}

public static void AppendStringToFile(string fileName, string plainText, byte[] key, byte[] iv)
{
    using (Rijndael algo = Rijndael.Create())
    {
        algo.Key = key;
        // The IV is set below
        algo.Mode = CipherMode.CBC;
        algo.Padding = PaddingMode.PKCS7;

        // Create the streams used for encryption.
        using (FileStream file = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
        {
            byte[] previous = null;
            int previousLength = 0;

            long length = file.Length;

            // No check is done that the file is correct!
            if (length != 0)
            {
                // The IV length is equal to the block length
                byte[] block = new byte[iv.Length];

                if (length >= iv.Length * 2)
                {
                    // At least 2 blocks, take the penultimate block
                    // as the IV
                    file.Position = length - iv.Length * 2;
                    file.Read(block, 0, block.Length);
                    algo.IV = block;
                }
                else
                {
                    // A single block present, use the IV given
                    file.Position = length - iv.Length;
                    algo.IV = iv;
                }

                // Read the last block
                file.Read(block, 0, block.Length);

                // And reposition at the beginning of the last block
                file.Position = length - iv.Length;

                // We use a MemoryStream because the CryptoStream
                // will close the Stream at the end
                using (var ms = new MemoryStream(block))
                // Create a decrytor to perform the stream transform.
                using (ICryptoTransform decryptor = algo.CreateDecryptor())
                using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                {
                    // Read all data from the stream. The decrypted last
                    // block can be long up to block length characters
                    // (so up to iv.Length) (this with AES + CBC)
                    previous = new byte[iv.Length];
                    previousLength = cs.Read(previous, 0, previous.Length);
                }
            }
            else
            {
                // Use the IV given
                algo.IV = iv;
            }

            // Create an encryptor to perform the stream transform.
            using (ICryptoTransform encryptor = algo.CreateEncryptor())
            using (CryptoStream cs = new CryptoStream(file, encryptor, CryptoStreamMode.Write))
            using (StreamWriter sw = new StreamWriter(cs))
            {
                // Rewrite the last block, if present. We even skip
                // the case of block present but empty
                if (previousLength != 0)
                {
                    cs.Write(previous, 0, previousLength);
                }

                // Write all data to the stream.
                sw.Write(plainText);
            }
        }
    }
}

public static string ReadStringFromFile(string fileName, byte[] key, byte[] iv)
{
    string plainText;

    using (Rijndael algo = Rijndael.Create())
    {
        algo.Key = key;
        algo.IV = iv;
        algo.Mode = CipherMode.CBC;
        algo.Padding = PaddingMode.PKCS7;

        // Create the streams used for decryption.
        using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
        // Create a decrytor to perform the stream transform.
        using (ICryptoTransform decryptor = algo.CreateDecryptor())
        using (CryptoStream cs = new CryptoStream(file, decryptor, CryptoStreamMode.Read))
        using (StreamReader sr = new StreamReader(cs))
        {
            // Read all data from the stream.
            plainText = sr.ReadToEnd();
        }
    }

    return plainText;
}

使用示例:

var key = Encoding.UTF8.GetBytes("Simple key");
var iv = Encoding.UTF8.GetBytes("Simple IV");

Array.Resize(ref key, 128 / 8);
Array.Resize(ref iv, 128 / 8);

if (File.Exists("test.bin"))
{
    File.Delete("test.bin");
}

for (int i = 0; i < 100; i++)
{
    AppendStringToFile("test.bin", string.Format("{0},", i), key, iv);
}

string plainText = ReadStringFromFile("test.bin", key, iv);

作品如何AppendStringToFile?三种情况:

  • 空文件:asWriteStringToFile
  • 具有单个块的文件:该块的 IV 是作为参数传递的 IV。该块被解密然后与传递的一起重新加密plainText
  • 具有多个块的文件:最后一个块的 IV 是倒数第二个块。所以倒数第二个块被读取,并用作IV(作为参数传递的IV被忽略)。最后一个块被解密,然后与传递的plainText. 为了重新加密最后一个块,使用的 IV 是倒数第二个块。
于 2015-06-16T09:50:05.800 回答