1

为了将 AES 加密文本作为std::istream解析器组件提供,我正在尝试创建一个std::streambuf包装 vanilla crypto++ 加密/解密的实现。

main()函数调用以下函数来比较我的包装器和 vanilla 实现:

  • EncryptFile()- 使用我的 streambuf 实现加密文件
  • DecryptFile()- 使用我的 streambuf 实现解密文件
  • EncryptFileVanilla()- 使用 vanilla crypto++ 加密文件
  • DecryptFileVanilla()- 使用 vanilla crypto++ 解密文件

问题是虽然EncryptFile()和创建的加密文件EncryptFileVanilla()是相同的。创建的解密文件DecryptFile()不正确,比创建的文件少 16 个字节DecryptFileVanilla()。可能不是巧合,块大小也是 16。

我认为问题一定出在 中CryptStreamBuffer::GetNextChar(),但我已经盯着它和 crypto++ 文档看了好几个小时了。

任何人都可以帮助/解释吗?

std::streambuf也欢迎任何其他关于我的实施多么糟糕或幼稚的评论;-)

谢谢,

汤姆

// Runtime Includes
#include <iostream>

// Crypto++ Includes
#include "aes.h"
#include "modes.h"      // xxx_Mode< >
#include "filters.h"    // StringSource and
                        // StreamTransformation
#include "files.h"

using namespace std;

class CryptStreamBuffer: public std::streambuf {

public:

    CryptStreamBuffer(istream& encryptedInput, CryptoPP::StreamTransformation& c);

    CryptStreamBuffer(ostream& encryptedOutput, CryptoPP::StreamTransformation& c);

    ~CryptStreamBuffer();

protected:
    virtual int_type overflow(int_type ch = traits_type::eof());

    virtual int_type uflow();

    virtual int_type underflow();

    virtual int_type pbackfail(int_type ch);

    virtual int sync();

private:
    int GetNextChar();

    int m_NextChar; // Buffered character

    CryptoPP::StreamTransformationFilter* m_StreamTransformationFilter;

    CryptoPP::FileSource* m_Source;

    CryptoPP::FileSink* m_Sink;

}; // class CryptStreamBuffer

CryptStreamBuffer::CryptStreamBuffer(istream& encryptedInput, CryptoPP::StreamTransformation& c) :
    m_NextChar(traits_type::eof()),
    m_StreamTransformationFilter(0),
    m_Source(0),
    m_Sink(0) {

    m_StreamTransformationFilter = new CryptoPP::StreamTransformationFilter(c, 0, CryptoPP::BlockPaddingSchemeDef::PKCS_PADDING);
    m_Source = new CryptoPP::FileSource(encryptedInput, false, m_StreamTransformationFilter);
}

CryptStreamBuffer::CryptStreamBuffer(ostream& encryptedOutput, CryptoPP::StreamTransformation& c) :
    m_NextChar(traits_type::eof()),
    m_StreamTransformationFilter(0),
    m_Source(0),
    m_Sink(0) {

    m_Sink = new CryptoPP::FileSink(encryptedOutput);
    m_StreamTransformationFilter = new CryptoPP::StreamTransformationFilter(c, m_Sink, CryptoPP::BlockPaddingSchemeDef::PKCS_PADDING);
}

CryptStreamBuffer::~CryptStreamBuffer() {

    if (m_Sink) {
        delete m_StreamTransformationFilter;
        // m_StreamTransformationFilter owns and deletes m_Sink.
    }
    if (m_Source) {
        delete m_Source;
        // m_Source owns and deletes m_StreamTransformationFilter.
    }
}

CryptStreamBuffer::int_type CryptStreamBuffer::overflow(int_type ch) {

    return m_StreamTransformationFilter->Put((byte)ch);
}

CryptStreamBuffer::int_type CryptStreamBuffer::uflow() {

    int_type result = GetNextChar();

    // Reset the buffered character
    m_NextChar = traits_type::eof();

    return result;
}

CryptStreamBuffer::int_type CryptStreamBuffer::underflow() {

    return GetNextChar();
}

CryptStreamBuffer::int_type CryptStreamBuffer::pbackfail(int_type ch) {

    return traits_type::eof();
}

int CryptStreamBuffer::sync() {

    // TODO: Not sure sync is the correct place to be doing this.
    //       Should it be in the destructor?
    if (m_Sink) {
        m_StreamTransformationFilter->MessageEnd();
        // m_StreamTransformationFilter->Flush(true);
    }

    return 0;
}

int CryptStreamBuffer::GetNextChar() {

    // If we have a buffered character do nothing
    if (m_NextChar != traits_type::eof()) {
        return m_NextChar;
    }

    // If there are no more bytes currently available then pump the source
    if (m_StreamTransformationFilter->MaxRetrievable() == 0) {
        m_Source->Pump(1024);
    }

    // Retrieve the next byte
    byte nextByte;
    size_t noBytes = m_StreamTransformationFilter->Get(nextByte);
    if (0 == noBytes) {
        return traits_type::eof();
    }

    // Buffer up the next character
    m_NextChar = nextByte;

    return m_NextChar;
}

void InitKey(byte key[]) {

    key[0] = -62;
    key[1] = 102;
    key[2] = 78;
    key[3] = 75;
    key[4] = -96;
    key[5] = 125;
    key[6] = 66;
    key[7] = 125;
    key[8] = -95;
    key[9] = -66;
    key[10] = 114;
    key[11] = 22;
    key[12] = 48;
    key[13] = 111;
    key[14] = -51;
    key[15] = 112;
}

/** Decrypt using my CryptStreamBuffer */
void DecryptFile(const char* sourceFileName, const char* destFileName) {

    ifstream ifs(sourceFileName, ios::in | ios::binary);
    ofstream ofs(destFileName, ios::out | ios::binary);

    byte key[CryptoPP::AES::DEFAULT_KEYLENGTH];
    InitKey(key);

    CryptoPP::ECB_Mode<CryptoPP::AES>::Decryption decryptor(key, sizeof(key));

    if (ifs) {
        if (ofs) {
            CryptStreamBuffer cryptBuf(ifs, decryptor);
            std::istream decrypt(&cryptBuf);

            int c;
            while (EOF != (c = decrypt.get())) {
                ofs << (char)c;
            }
            ofs.flush();
        }
        else {
            std::cerr << "Failed to open file '" << destFileName << "'." << endl;
        }
    }
    else {
        std::cerr << "Failed to open file '" << sourceFileName << "'." << endl;
    }  
}

/** Encrypt using my CryptStreamBuffer */
void EncryptFile(const char* sourceFileName, const char* destFileName) {

    ifstream ifs(sourceFileName, ios::in | ios::binary);
    ofstream ofs(destFileName, ios::out | ios::binary);

    byte key[CryptoPP::AES::DEFAULT_KEYLENGTH];
    InitKey(key);

    CryptoPP::ECB_Mode<CryptoPP::AES>::Encryption encryptor(key, sizeof(key));

    if (ifs) {
        if (ofs) {
            CryptStreamBuffer cryptBuf(ofs, encryptor);
            std::ostream encrypt(&cryptBuf);

            int c;
            while (EOF != (c = ifs.get())) {
                encrypt << (char)c;
            }
            encrypt.flush();
        }
        else {
            std::cerr << "Failed to open file '" << destFileName << "'." << endl;
        }
    }
    else {
        std::cerr << "Failed to open file '" << sourceFileName << "'." << endl;
    }  
}

/** Decrypt using vanilla crypto++ */
void DecryptFileVanilla(const char* sourceFileName, const char* destFileName) {

    byte key[CryptoPP::AES::DEFAULT_KEYLENGTH];
    InitKey(key);

    CryptoPP::ECB_Mode<CryptoPP::AES>::Decryption decryptor(key, sizeof(key));

    CryptoPP::FileSource(sourceFileName, true,
      new CryptoPP::StreamTransformationFilter(decryptor,
        new CryptoPP::FileSink(destFileName), CryptoPP::BlockPaddingSchemeDef::PKCS_PADDING
      ) // StreamTransformationFilter
    ); // FileSource
}

/** Encrypt using vanilla crypto++ */
void EncryptFileVanilla(const char* sourceFileName, const char* destFileName) {

    byte key[CryptoPP::AES::DEFAULT_KEYLENGTH];
    InitKey(key);

    CryptoPP::ECB_Mode<CryptoPP::AES>::Encryption encryptor(key, sizeof(key));

    CryptoPP::FileSource(sourceFileName, true,
      new CryptoPP::StreamTransformationFilter(encryptor,
        new CryptoPP::FileSink(destFileName), CryptoPP::BlockPaddingSchemeDef::PKCS_PADDING
      ) // StreamTransformationFilter
    ); // FileSource
}

int main(int argc, char* argv[])
{
    EncryptFile(argv[1], "encrypted.out");
    DecryptFile("encrypted.out", "decrypted.out");
    EncryptFileVanilla(argv[1], "encrypted_vanilla.out");
    DecryptFileVanilla("encrypted_vanilla.out", "decrypted_vanilla.out");
    return 0;
}
4

2 回答 2

5

在使用 crypto++ 的调试版本后,发现缺少的是对 StreamTransformationFilter 的调用,通知它不会有更多来自 Source 的内容,并且它应该结束最后几个字节的处理,包括填充.

CryptStreamBuffer::GetNextChar()

代替:

// If there are no more bytes currently available then pump the source
if (m_StreamTransformationFilter->MaxRetrievable() == 0) {
    m_Source->Pump(1024);
}

和:

// If there are no more bytes currently available from the filter then
// pump the source.
if (m_StreamTransformationFilter->MaxRetrievable() == 0) {
    if (0 == m_Source->Pump(1024)) {
        // This seems to be required to ensure the final bytes are readable
        // from the filter.
        m_StreamTransformationFilter->ChannelMessageEnd(CryptoPP::DEFAULT_CHANNEL);
    }
}

我没有声称这是最好的解决方案,只是我通过反复试验发现的一个似乎有效的解决方案。

于 2010-06-14T13:05:38.330 回答
3

如果您的输入缓冲区不是 16 字节块的复数,则需要用虚拟字节填充最后一个块。如果最后一个块小于 16 字节,它会被 crypto++ 丢弃并且不加密。解密时,您需要截断虚拟字节。您所指的“另一种方式”已经为您进行了加法和截断。那么虚拟字节应该是什么,知道它们有多少,因此应该被截断?我使用以下模式:用虚拟计数的值填充每个字节。

例子:你需要加8个字节?将它们设置为 0x08、0x08、0x08、0x08、0x08、0x08、0x08、0x08。您需要添加 3 个字节吗?将它们设置为 0x03、0x03、0x03 等。

解密时,获取输出缓冲区最后一个字节的值。假设它是 N。检查最后 N 个字节的值是否等于 N。如果为真,则截断。

更新:

CryptStreamBuffer::CryptStreamBuffer(istream& encryptedInput, CryptoPP::StreamTransformation& c) :
    m_NextChar(traits_type::eof()),
    m_StreamTransformationFilter(0),
    m_Source(0),
    m_Sink(0) {

    m_StreamTransformationFilter = new CryptoPP::StreamTransformationFilter(c, 0, CryptoPP::BlockPaddingSchemeDef::ZEROS_PADDING);
    m_Source = new CryptoPP::FileSource(encryptedInput, false, m_StreamTransformationFilter);
}

CryptStreamBuffer::CryptStreamBuffer(ostream& encryptedOutput, CryptoPP::StreamTransformation& c) :
    m_NextChar(traits_type::eof()),
    m_StreamTransformationFilter(0),
    m_Source(0),
    m_Sink(0) {

    m_Sink = new CryptoPP::FileSink(encryptedOutput);
    m_StreamTransformationFilter = new CryptoPP::StreamTransformationFilter(c, m_Sink, CryptoPP::BlockPaddingSchemeDef::ZEROS_PADDING);
}

设置 ZEROS_PADDING 使您的代码工作(在文本文件上测试)。但是为什么它不适用于 DEFAULT_PADDING - 我还没有找到原因。

于 2010-06-11T16:18:19.057 回答