rsa加密如何在C++中实现

   2024-10-07 9740
核心提示:在C++中实现RSA加密需要使用第三方库,比如OpenSSL或Crypto++. 这里我给出一个使用Crypto++库实现RSA加密的示例代码:#include i

在C++中实现RSA加密需要使用第三方库,比如OpenSSL或Crypto++. 这里我给出一个使用Crypto++库实现RSA加密的示例代码:

#include <iostream>#include <string>#include <cryptopp/rsa.h>#include <cryptopp/osrng.h>#include <cryptopp/base64.h>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密钥对,然后使用公钥加密明文。最后输出加密后的数据。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号