c++ openssl rsa 加解密
时间: 2024-10-23 09:20:20 浏览: 32
c++通过openssl实现rsa加密解密【windows版】
在 C++ 中使用 OpenSSL 进行 RSA 加密和解密操作,首先需要包含 OpenSSL 的头文件,并确保已经安装了库。以下是基本的步骤:
1. **初始化 OpenSSL**:
```cpp
#include <openssl/rsa.h>
#include <openssl/pem.h>
```
2. **加载 RSA 私钥和公钥**:
- 加载私钥(`.pem` 或 `.der` 格式):
```cpp
FILE* privateKeyFile = fopen("private_key.pem", "rb");
RSA* privKey = PEM_read_RSAPrivateKey(privateKeyFile, NULL, NULL, NULL);
```
- 加载公钥(`.pem` 格式):
```cpp
FILE* publicKeyFile = fopen("public_key.pem", "rb");
RSA* pubKey = PEM_read_RSA_PUBKEY(publicKeyFile, NULL, NULL, NULL);
```
3. **加密数据** (使用公钥):
```cpp
unsigned char encryptedData[512];
int encryptionResult = RSA_public_encrypt(messageSize, message, encryptedData, pubKey, RSA_PKCS1_OAEP_PADDING);
if (encryptionResult <= 0) {
// 处理错误
}
```
4. **解密数据** (使用私钥):
```cpp
unsigned char decryptedData[512];
int decryptionResult = RSA_private_decrypt(encryptedDataSize, encryptedData, decryptedData, privKey, RSA_PKCS1_OAEP_PADDING);
if (decryptionResult <= 0) {
// 处理错误
}
const char* decryptedMessage = reinterpret_cast<const char*>(decryptedData);
```
5. **清理资源**:
```cpp
fclose(privateKeyFile);
fclose(publicKeyFile);
RSA_free(privKey);
RSA_free(pubKey);
```
阅读全文