Crypto++ 输出数据长度

Crypto++ output data length

我正在尝试使用 Crypto++ 库中的 AES 加密:

CBC_Mode<AES>::Encryption e;

我有一个二进制数据块需要加密。 class 似乎为此提供了一个名为 ProcessData 的方法:

virtual void ProcessData(byte *outString, const byte *inString, size_t length);

看起来最后一个参数是输入数据的大小。不清楚的是为什么该方法不 return 我加密数据的大小。是否假设输出数据块的大小与输入数据块的长度完全相同?即使输入数据的大小只有一个字节,这是否有效?问候。

virtual void ProcessData(byte *outString, const byte *inString, size_t length);

Looks like the last parameter is the size of the input data. What is not clear is why the method does not return me the size of the encrypted data...

ProcessData 是所有块密码的主力(但不是流密码或其他类型的对象)。另请参阅 Crypto++ 手册和 cryptlib.h File Referencecryptlib.h 被描述为 "Abstract base classes that provide a uniform interface to this library".

ProcessData 对数据块大小的长度进行操作。所以INSIZE等于OUTSIZE等于BLOCKSIZE。请注意,没有 INSIZEOUTSIZE - 我将它们用于讨论。每个块密码将为 BLOCKSIZE 提供一个常量。会有AES::BLOCKSIZEDES_EDE::BLOCKSIZE

通常您不会直接使用ProcessData。您可以直接使用它,但您将对所有相关细节负责(更多细节见下文)。

通常您使用 StreamTransformationFilter,但原因并不明显。 StreamTransformationFilter 根据需要提供输入缓冲、输出缓冲和填充。在 wiki 的 Init-Update-Final 中对其进行了简要讨论。

这是 Crypto++ wiki 上 CBC mode 示例的实际情况:

try
{
    cout << "plain text: " << plain << endl;

    CBC_Mode< AES >::Encryption e;
    e.SetKeyWithIV( key, key.size(), iv );

    // The StreamTransformationFilter adds padding
    //  as required. ECB and CBC Mode must be padded
    //  to the block size of the cipher.
    StringSource ss( plain, true, 
        new StreamTransformationFilter( e,
            new StringSink( cipher )
        ) // StreamTransformationFilter      
    ); // StringSource
}
catch( const CryptoPP::Exception& e )
{
    cerr << e.what() << endl;
    exit(1);
}

在上面,CBC_modeStreamTransformationFilter 一起工作可以得到你想要的结果。 CBC_mode 调用 ProcessData 并处理密码链细节。 StreamTransformationFilter 以其首选大小提供纯文本。如果没有足够的纯文本,那么 StreamTransformationFilter 会在输入时对其进行缓冲。如果没有输出缓冲区,那么 StreamTransformationFilter 也会缓冲密文。

StreamTransformationFilter 也将根据需要应用填充。有一个默认填充,但您可以覆盖它。 StreamTransformationFilter 知道要应用什么填充,因为它询问模式 (CBC_mode) 是否需要填充以及填充应该是什么。


... Is it assumed that the size of output data block is exactly the same as the length of input data block? Is this valid even if the size of input data is just one byte?

这就是 StreamTransformationFilter 符合等式的地方。

一定要查看维基上的 Init-Update-Final。如果您习惯于 Java 或 OpenSSL 编程,它应该为您提供粘合剂。它应该对你有帮助"make it click"。