c++ - 将 AES 密文作为参数传递

标签 c++ encryption aes encryption-symmetric crypto++

我正在尝试编写 2 个不同的函数来使用 cryptopp 中的 AES 加密和解密数据。我想将密文作为参数传递给解密函数。然而,在解密功能上,它接收到一些特殊符号作为密文,因此无法正确解密。请帮忙。

// -- AES encryption function ----------
void Security_packetAgent::encryption(char out[])
{ 
    std::string plaintext = out;
    std::string ciphertext = "";

    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
    stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() + 1 );
    stfEncryptor.MessageEnd();

    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

    for( int i = 0; i < ciphertext.size(); i++ )
    {
        std::cout << "0x" << std::hex << (0xFF & static_cast<byte>(ciphertext[i])) << " ";
    }

    std::cout<<"\nMessage encrypted ...";
    std::cout << std::endl << std::endl;
    sprintf(out, "%s", ciphertext.c_str());
    printf("Final Data: %s : %s ", out, reinterpret_cast<const unsigned char*>(ciphertext.c_str()));
}

// ---- AES decryption  ------------------
void Security_packetAgent::decryption(char out[])
{ 
    cout<<"\nCipher recieved: "<<out;
    std::cout<<"\nEntered decryption ..";
    std::string ciphertext = out;
    std::string decryptedtext;

    cout<<"\nCipher recieved: "<<reinterpret_cast<const unsigned char*>( ciphertext.c_str());
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
    stfDecryptor.MessageEnd();

    std::cout << "Decrypted Text: " << std::endl;
    std::cout << decryptedtext;
    std::cout << std::endl << std::endl;    
}

最佳答案

如果 char* 指向的东西不是' 文本字符串,例如加密数据。

std::string ciphertext = out;

ciphertext 的构造将在到达 0 字节时停止从 out 复制。相反,您还需要传入加密数据的 length 并使用 std::string(const char* data, size_t size) 构造函数。

std::string ciphertext(out, outSize);

或者,您也可以使用带有开始和结束迭代器的构造函数。

关于c++ - 将 AES 密文作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16484429/

相关文章:

c# - RFC2898DeriveBytes 如何生成 AES key ?

linux - 加密文件保存到磁盘

sql - 没有证书的 MS SQL 列加密

c++ - 将 vector 写入文件并读回

c++ - Visual Studio C++ 编译器优化破坏代码?

encryption - 以编程方式读取 vi 加密文件

cocoa - 有AES加密解密的cocoa源代码吗?

c++ - 如何在 C++ 中创建动态 DLL 库,以替代遗留的 Fortran DLL

c++ - QtQuick、动态图像和 C++

CFB 中的 C# AES 加密,其中明文长度等于加密长度