在C++中实现RSA加密需要使用第三方库,比如OpenSSL或Crypto++. 这里我给出一个使用Crypto++库实现RSA加密的示例代码:
#include #include #include #include #include using namespace CryptoPP; std::string rsaEncrypt(const std::string& msg, const RSA::PublicKey& key) { std::string encrypted; RSAES_OAEP_SHA_Encryptor encryptor(key); StringSource(msg, true, new PK_EncryptorFilter(rng, encryptor, new StringSink(encrypted))); return encrypted; } int main() { AutoSeededRandomPool rng; // 生成RSA密钥对 RSA::PrivateKey privateKey; RSA::PublicKey publicKey; privateKey.GenerateRandomWithKeySize(rng, 2048); privateKey.MakePublicKey(publicKey); // 待加密的明文 std::string msg = "Hello, world!"; // 使用公钥加密明文 std::string encrypted = rsaEncrypt(msg, publicKey); std::cout << "Encrypted message: " << encrypted << std::endl; return 0; }
在上面的代码中,我们使用Crypto++库提供的RSAES_OAEP_SHA_Encryptor类进行RSA加密,使用PK_EncryptorFilter类进行过滤加密数据。首先生成RSA密钥对,然后使用公钥加密明文。最后输出加密后的数据。