c++ - 在二进制数据(密文)上使用 CryptoPP::Base64Encoder

标签 c++ base64 crypto++

我在使用 CryptoPP 时遇到问题。我正在使用 AES,并且想通过将其编码为 base64 来表示二进制密文。

我的问题是我在运行以下代码时随机出现断言错误:

std::string encoded;
// ciphertext is of type std::string from AES
CryptoPP::StringSource(ciphertext, true, 
    new CryptoPP::Base64Encoder(new CryptoPP::StringSink(encoded)));

具体的断言错误是:

Assertion failed: m_allocated, file include\cryptopp\secblock.h, line 197

由于这种“随机”行为,它让我相信问题出在密文的内容中。

我的问题是:我这样做的方式是否正确?我被难住了一段时间,并且一直在研究但没有成功。我能找到的最接近的是:http://www.mail-archive.com/cryptopp-users@googlegroups.com/msg06053.html

我的完整实现是:

std::string key = "key";
std::string in = "This is a secret message.";

CryptoPP::SHA1 sha;

byte digest[CryptoPP::SHA1::DIGESTSIZE];
sha.CalculateDigest(digest, reinterpret_cast<const byte *>(key.c_str()), key.length());

byte iv[CryptoPP::AES::BLOCKSIZE];
memset(iv, 0x00, CryptoPP::AES::BLOCKSIZE);

CryptoPP::AES::Encryption encrypt(reinterpret_cast<const byte *>(digest), CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbc_encrypt(encrypt, iv);

std::string ciphertext;
CryptoPP::StreamTransformationFilter encryptor(cbc_encrypt,
    new CryptoPP::StringSink(ciphertext));
encryptor.Put(reinterpret_cast<const unsigned char *>(in.c_str()), in.length() + 1);
encryptor.MessageEnd();

std::string encoded;
CryptoPP::StringSource(ciphertext, true, 
    new CryptoPP::Base64Encoder(new CryptoPP::StringSink(encoded)));

最佳答案

My question is: Am I doing this the correct way?

是的,代码没问题(digest.erase(); 除外)。


I've been stumped for a while, and have been researching a bit without success.

在内存检查器下运行它。 Valgrind 或 Clang Asan(地址 sanitizer )。


The closest thing I can find is: http://www.mail-archive.com/cryptopp-users@googlegroups.com/msg06053.html

我过去也遇到过这种说法。我不记得是 iOS 还是 Linux。我认为是带有特定版本 GCC(可能是 4.4 或 4.5)的 Linux。


My problem is that I am randomly getting assertion errors when running the following code:

CryptoPP::StringSource(ciphertext, true, 
    new CryptoPP::Base64Encoder(new CryptoPP::StringSink(encoded)));

将上面的改成这样:

CryptoPP::StringSource ss(ciphertext, true, 
    new CryptoPP::Base64Encoder(new CryptoPP::StringSink(encoded)));

GCC 的一个版本在匿名声明方面存在问题。它会过早开始运行对象析构函数。

关于c++ - 在二进制数据(密文)上使用 CryptoPP::Base64Encoder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8015495/

相关文章:

c++ - QML 对象初始化期间函数调用的顺序是确定性的吗?

c++ - 将 while(1) 循环中的文本插入到 QT 中的文本编辑器

c# - 为什么我的 Base64 编码哈希只包含 28 个字符?

c# - 如何将 Crypto++ RSA 与 C# RSA 加密服务提供商同步?

c++ - 基类的 constexpr 地址

java - 为什么我需要在这个加密中使用 Base64

java - 如何知道Java类使用什么Base64编码变体?

c++ - 为 Crypto++ 构建和链接测试代码

c++ - 我正在使用 Crypto++ 进行 RSA 加密。我的纯文本超过了 FixedMaxPlaintextLength。我应该怎么办?

c++ - 访问条件类成员的方法仅在被调用时不编译