RSA公钥加密C++完整代码实现
时间: 2024-12-11 18:24:29 浏览: 93
RSA(Rivest-Shamir-Adleman)是一种非对称加密算法,它由三个主要组成部分:密钥生成、加密和解密。这里是一个简单的C++代码示例,展示了如何实现RSA公钥加密的基本步骤:
#include <iostream>
#include <string>
#include <vector>
#include <openssl/bio.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
// RSA公钥和私钥结构体
struct RSAPair {
RSA* pub_key;
RSA* priv_key;
};
// 密钥生成函数
RSAPair generateKeys(int key_size) {
RSA* rsa = RSA_new();
BIGNUM* e = BN_new(), *n = BN_new();
// 设置公钥参数
RSA_generate_key_ex(rsa, key_size, e, n);
RSAPair pair;
pair.pub_key = rsa;
// 私钥需要设置为p、q以及它们之间的欧拉函数phi(n)
// 这里简化了演示,实际应用中应使用更安全的方式获取素数因子
BIGNUM p = BN_dup(n), q = BN_dup(n);
BN_sub_word(p, 1); // p = n - 1 (假设n大于2)
BN_sub_word(q, 1); // q = n - 1
BN_mod_inverse(e, p, q); // 计算e^-1 mod phi(n)
pair.priv_key = RSA_new();
RSA_set_factors(pair.priv_key, p, q);
RSA_set_public_key(pair.priv_key, rsa);
return pair;
}
// 将字符串转换为大整数用于RSA操作
std::string strToBN(const std::string& input, const RSAPair& key) {
int len = BN_num_bytes(key.pub_key->n);
unsigned char buffer[len + 1];
BN_bn2bin(key.pub_key->n, buffer);
buffer[len] = '\0';
return reinterpret_cast<const char*>(buffer), len;
}
// 公钥加密
std::string encrypt(const std::string& plaintext, const RSAPair& key) {
std::string message = strToBN(plaintext, key);
BIO* bio = BIO_new(BIO_s_mem());
if (!BIO_write(bio, message.c_str(), message.size())) {
throw std::runtime_error("Error writing to bio");
}
unsigned char encrypted[256]; // 预设足够大的数组
int enc_len = RSA_public_encrypt(message.size(), bio->data(), encrypted, key.pub_key, RSA_PKCS1_OAEP_PADDING);
BIO_free_all(bio);
if (enc_len <= 0) {
throw std::runtime_error("Encryption failed");
}
return std::string(reinterpret_cast<char*>(encrypted), enc_len);
}
int main() {
try {
RSAPair keys = generateKeys(2048);
std::string plaintext = "Hello, World!";
std::string ciphertext = encrypt(plaintext, keys);
// 输出和存储加密后的数据
std::cout << "Encrypted: " << ciphertext << std::endl;
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
RSA_free(keys.pub_key);
RSA_free(keys.priv_key);
BN_free(e);
BN_free(n);
return 0;
}
相关推荐



















