以下是使用OpenSSL在C++中实现公钥加密和私钥解密的示例代码。这个例子展示了如何生成RSA密钥对,使用公钥加密数据,然后使用私钥解密数据。
```cpp
#include <iostream>
#include <string>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
// 错误处理函数
void handleErrors() {
ERR_print_errors_fp(stderr);
abort();
}
// 生成RSA密钥对
RSA* generateRSAKeyPair(int keyLength) {
RSA *rsa = RSA_new();
BIGNUM *bne = BN_new();
BN_set_word(bne, RSA_F4);
if (RSA_generate_key_ex(rsa, keyLength, bne, nullptr) != 1) {
handleErrors();
}
BN_free(bne);
return rsa;
}
// 使用公钥加密
std::string publicEncrypt(RSA* rsa, const std::string& message) {
int rsaSize = RSA_size(rsa);
std::vector<unsigned char> encryptedData(rsaSize);
int encryptedLength = RSA_public_encrypt(message.length(),
reinterpret_cast<const unsigned char*>(message.c_str()),
encryptedData.data(),
rsa,
RSA_PKCS1_PADDING);
if (encryptedLength == -1) {
handleErrors();
}
return std::string(reinterpret_cast<char*>(encryptedData.data()), encryptedLength);
}
// 使用私钥解密
std::string privateDecrypt(RSA* rsa, const std::string& encryptedMessage) {
int rsaSize = RSA_size(rsa);
std::vector<unsigned char> decryptedData(rsaSize);
int decryptedLength = RSA_private_decrypt(encryptedMessage.length(),
reinterpret_cast<const unsigned char*>(encryptedMessage.c_str()),
decryptedData.data(),
rsa,
RSA_PKCS1_PADDING);
if (decryptedLength == -1) {
handleErrors();
}
return std::string(reinterpret_cast<char*>(decryptedData.data()), decryptedLength);
}
int main() {
// 初始化OpenSSL
ERR_load_crypto_strings();
OpenSSL_add_all_algorithms();
// 生成RSA密钥对
RSA* rsaKeyPair = generateRSAKeyPair(2048);
// 原始消息
std::string originalMessage = "Hello, OpenSSL RSA Encryption!";
std::cout << "Original message: " << originalMessage << std::endl;
// 使用公钥加密
std::string encryptedMessage = publicEncrypt(rsaKeyPair, originalMessage);
std::cout << "Encrypted message: " << encryptedMessage << std::endl;
// 使用私钥解密
std::string decryptedMessage = privateDecrypt(rsaKeyPair, encryptedMessage);
std::cout << "Decrypted message: " << decryptedMessage << std::endl;
// 清理
RSA_free(rsaKeyPair);
EVP_cleanup();
ERR_free_strings();
return 0;
}
```
这个程序执行以下步骤:
1. 初始化OpenSSL库。
2. 生成一个2048位的RSA密钥对。
3. 定义一个原始消息。
4. 使用公钥加密消息。
5. 使用私钥解密加密后的消息。
6. 打印原始消息、加密后的消息和解密后的消息。
7. 清理并释放资源。
要编译和运行这个程序,你需要链接OpenSSL库。在Linux系统上,你可以使用以下命令编译:
```bash
g++ -o rsa_example rsa_example.cpp -lssl -lcrypto
```
然后运行:
```bash
./rsa_example
```
注意事项:
1. 这个例子使用RSA算法进行加密和解密。RSA适用于小量数据的加密,对于大量数据,通常会使用混合加密系统(如使用RSA加密对称密钥,然后使用对称密钥加密大量数据)。
2. 在实际应用中,你可能需要将公钥和私钥保存到文件中,而不是每次都生成新的密钥对。
3. 错误处理在这个例子中比较简单。在生产环境中,你应该实现更健壮的错误处理机制。
4. 这个例子直接使用了RSA函数。在更现代的OpenSSL版本中,推荐使用EVP接口,它提供了更高级别的抽象和更好的跨平台兼容性。
5. 安全性是密码学应用的关键。在实际应用中,确保遵循最佳安全实践,如适当的密钥管理、安全的随机数生成等。