温馨提示×

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

c++
小樊
133
2024-07-12 15:01:31
栏目: 编程语言

在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密钥对,然后使用公钥加密明文。最后输出加密后的数据。

0