C# AES 加密 - 流模式自动添加 IV

标签 c# encryption aes encryption-symmetric initialization-vector

根据This Answer的评论来自 GregS,IV 应该放在 AES 加密数据前面(假设我没读错):

Put it before the cipher. That way you can have decrypt in streaming mode.

在我看来,GregS 暗示有一种流模式,可以自动添加/解析加密中使用的 IV。

这是真的吗?

我目前正在手动将 IV 添加到加密数据之前,并在解密之前手动将密码拆分为 IV 和数据。有没有一种方法可以自动执行此操作?


供引用:

这就是我现在正在做的事情:

加密方法:

public byte[] Encrypt(byte[] data)
{
    // Generate IV
    var iv = new byte[BlockSize/8];
    new Random().NextBytes(iv);

    byte[] cipher = // encryption happens here

    // Prepend IV to Cipher
    var saltedCipher = new byte[iv.Length + cipher.Length];
    Buffer.BlockCopy(iv, 0, saltedCipher, 0, iv.Length);
    Buffer.BlockCopy(cipher, 0, saltedCipher, iv.Length, cipher.Length);

    return saltedCipher;
}

解密方法:

public byte[] Decrypt(byte[] saltedCipher)
{
    // Split saltedCipher into iv and cipher
    var iv = new byte[BlockSize/8];
    var cipher = new byte[saltedCipher.Length - iv.Length];
    Buffer.BlockCopy(buffer, 0, iv, 0, iv.Length);
    Buffer.BlockCopy(buffer, iv.Length, cipher, 0, cipher.Length);

    byte[] data = // decryption happens here

    return data;
}

最佳答案

仅使用 .NET 框架内置的方法,据我所知无法自动添加数据。有许多第三方库可以为您处理此问题,但 System.Security.Cryptography 中的库默认情况下不会。

通常,当您加密信息时,您会得到一个 header ,其中包含解密文件之前需要了解的所有相关信息,这些信息的内容根据软件的需求而有很大差异。对于您的简单示例,您的 header 只是

╔════════════════╦══════════════╦═══════════════════╦═════════════╗
║ Offset (bytes) ║ Size (bytes) ║ Encryption Status ║ Description ║
╠════════════════╬══════════════╬═══════════════════╬═════════════╣
║ 0              ║ BlockSize/8  ║  Unencrypted      ║ IV          ║
║ BlockSize/8    ║ Var.         ║  Encrypted        ║ Data Area   ║
╚════════════════╩══════════════╩═══════════════════╩═════════════╝

这就是您所需要的,因为您(我假设)是固定的 block 大小,您不需要任何额外的信息,例如 IV 长度或有关文件的任何元数据。

将其与更复杂的文件进行比较,例如 TrueCrypt 容器( The original site 在规范中不再存在,但 I found this mirror )

╔════════════════╦══════════════╦════════════════════════════╦══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╗
║ Offset (bytes) ║ Size (bytes) ║     Encryption Status      ║                                                                                                                         Description                                                                                                                          ║
╠════════════════╬══════════════╬════════════════════════════╬══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╣
║ 0              ║ 64           ║  Unencrypted§              ║  Salt                                                                                                                                                                                                                                                        ║
║ 64             ║ 4            ║  Encrypted                 ║  ASCII string "TRUE"                                                                                                                                                                                                                                         ║
║ 68             ║ 2            ║  Encrypted                 ║  Volume header format version (5)                                                                                                                                                                                                                            ║
║ 70             ║ 2            ║  Encrypted                 ║  Minimum program version required to open the volume                                                                                                                                                                                                         ║
║ 72             ║ 4            ║  Encrypted                 ║  CRC-32 checksum of the (decrypted) bytes 256-511                                                                                                                                                                                                            ║
║ 76             ║ 16           ║  Encrypted                 ║  Reserved (must contain zeroes)                                                                                                                                                                                                                              ║
║ 92             ║ 8            ║  Encrypted                 ║  Size of hidden volume (set to zero in non-hidden volumes)                                                                                                                                                                                                   ║
║ 100            ║ 8            ║  Encrypted                 ║  Size of volume                                                                                                                                                                                                                                              ║
║ 108            ║ 8            ║  Encrypted                 ║  Byte offset of the start of the master key scope                                                                                                                                                                                                            ║
║ 116            ║ 8            ║  Encrypted                 ║  Size of the encrypted area within the master key scope                                                                                                                                                                                                      ║
║ 124            ║ 4            ║  Encrypted                 ║  Flag bits (bit 0 set: system encryption; bit 1 set: non-system  in-place-encrypted/decrypted volume; bits 2–31 are reserved)                                                                                                                                ║
║ 128            ║ 4            ║  Encrypted                 ║  Sector size (in bytes)                                                                                                                                                                                                                                      ║
║ 132            ║ 120          ║  Encrypted                 ║  Reserved (must contain zeroes)                                                                                                                                                                                                                              ║
║ 252            ║ 4            ║  Encrypted                 ║  CRC-32 checksum of the (decrypted) bytes 64-251                                                                                                                                                                                                             ║
║ 256            ║ Var.         ║  Encrypted                 ║  Concatenated primary and secondary master keys**                                                                                                                                                                                                            ║
║ 512            ║ 65024        ║  Encrypted                 ║  Reserved (for system encryption, this item is omitted‡‡)                                                                                                                                                                                                    ║
║ 65536          ║ 65536        ║  Encrypted / Unencrypted§  ║  Area for hidden volume header (if there is no hidden volume within the volume, this area contains random data††). For  system encryption, this item is omitted.‡‡ See bytes 0–65535.                                                                        ║
║ 131072         ║ Var.         ║  Encrypted                 ║  Data area (master key scope). For system encryption, offset  may be different (depending on offset of system partition).                                                                                                                                    ║
║ S-131072‡      ║ 65536        ║  Encrypted / Unencrypted§  ║  Backup header (encrypted with a different header key derived using a different salt). For system encryption, this item is omitted.‡‡ See bytes 0–65535.                                                                                                     ║
║ S-65536‡       ║ 65536        ║  Encrypted / Unencrypted§  ║  Backup header for hidden volume (encrypted with a different header key derived using a different salt). If there is no hidden volume within the volume, this area contains random data.†† For system encryption, this item is omitted.‡‡ See bytes 0–65535. ║
╚════════════════╩══════════════╩════════════════════════════╩══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╝

* Provided that the options Quick Format and Dynamic are disabled and provided that the volume does not contain a filesystem that has been encrypted in place (note that TrueCrypt does not allow the user to create a hidden volume within such a volume).
† The encrypted areas of the volume header are encrypted in XTS mode using the primary and secondary header keys. For more information, see the section Encryption Scheme and the section Header Key Derivation, Salt, and Iteration Count.
‡ S denotes the size of the volume host (in bytes).
§ Note that the salt does not need to be encrypted, as it does not have to be kept secret [7] (salt is a sequence of random values).
** Multiple concatenated master keys are stored here when the volume is encrypted using a cascade of ciphers (secondary master keys are used for XTS mode).
†† See above in this section for information on the method used to fill free volume space with random data when the volume is created.
‡‡ Here, the meaning of "system encryption" does not include a hidden volume containing a hidden operating system.

因此,由于 header 的需求差异很大,.NET 框架将其留给开发人员自行设计。

关于C# AES 加密 - 流模式自动添加 IV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24962223/

相关文章:

azure - VS 2013 部分支持 azure v12 中的证书和对称 key

encryption - 没有 IV 的 AES 256 加密/解密

java - 'BadPaddingException : pad block corrupted' while decrypting using AES/ECB

Java 错误 : Input length must be multiple of 16 when decrypting with padded cipher

c# - Windows UWP BluetoothLE设备缓存

c# - Selenium:如何拦截请求

python - 对 python2 和 python3 使用相同代码的编码 + 加密 + pad 出现问题

用于 Android 的基于 Java 的加密库

c# - ASP.NET MVC 递归过程

c# - New-PSSession 和 Runspacepool 说明