我在使用 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)));