RSA公钥加密C++代码
时间: 2024-10-29 16:05:09 浏览: 37
RSA(Rivest-Shamir-Adleman)是一种非对称加密算法,由三名美国密码学家发明。它基于大数分解的难度,其中一个密钥(公钥)用于加密,另一个密钥(私钥)用于解密。以下是C++的一个简单示例,展示了如何生成公钥和私钥,并使用它们进行加密和解密:
```cpp
#include <openssl/pem.h>
#include <openssl/rsa.h>
// RSA key pair generation (1024-bit default)
RSA* generate_rsa_key_pair() {
RSA* rsa = RSA_new();
BIGNUM* e = BN_new(), *n = BN_new();
// Generate public exponent e (usually 65537)
BN_set_word(e, RSA_F4);
// Generate a large random prime p
unsigned int bits = RSA_num_bits(rsa);
BIGNUM* p = BN_generate_prime_ex(NULL, bits, NULL, BN_MONT_CTX, NULL);
if (!p) {
perror("Failed to generate prime p");
exit(1);
}
// Generate another large random prime q and calculate n = p*q
BIGNUM* q = BN_generate_prime_ex(NULL, bits, NULL, BN_MONT_CTX, NULL);
if (!q) {
perror("Failed to generate prime q");
exit(1);
}
BN_mul(n, p, q, NULL); // n = p * q
// Calculate the modulus (public key)
RSA_set_n(rsa, n);
RSA_generate_key_ex(rsa, RSA_F4, e, NULL, NULL); // Generate private key
BN_free(p);
BN_free(q);
return rsa;
}
// Encrypt message using public key
std::string encrypt(const std::string& plaintext, RSA* pubkey) {
const int msg_len = plaintext.length();
unsigned char ciphertext[msg_len * 2 + 1]; // Add room for padding
int len;
if ((len = RSA_public_encrypt(msg_len, reinterpret_cast<const unsigned char*>(plaintext.c_str()), ciphertext, pubkey, RSA_PKCS1_OAEP_PADDING)) <= 0) {
perror("Encryption failed");
return "";
}
return std::string(reinterpret_cast<char*>(ciphertext), len);
}
// Decrypt message using private key
std::string decrypt(const std::string& ciphertext, RSA* privkey) {
const int crypted_len = ciphertext.length();
unsigned char decrypted_msg[crypted_len];
int len;
if ((len = RSA_private_decrypt(crypted_len, reinterpret_cast<const unsigned char*>(ciphertext.c_str()), decrypted_msg, privkey, RSA_PKCS1_OAEP_PADDING)) <= 0) {
perror("Decryption failed");
return "";
}
return std::string(reinterpret_cast<char*>(decrypted_msg), len);
}
int main() {
RSA* rsa = generate_rsa_key_pair();
// Use rsa for encryption and decryption...
RSA_free(rsa); // Don't forget to free memory when done
return 0;
}
```
注意:这个例子仅做教学演示,实际应用中你需要处理PEM文件的序列化和反序列化以及错误处理。
阅读全文