OpenSSL在C++中实现公钥加密和私钥解密

以下是使用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. 安全性是密码学应用的关键。在实际应用中,确保遵循最佳安全实践,如适当的密钥管理、安全的随机数生成等。
 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++ 可以使用 OpenSSL 库来实现公钥加密私钥解密。以下是一个简单的示例代码: ```c++ #include <openssl/rsa.h> #include <openssl/pem.h> int main() { // 生成 RSA 密钥对 RSA *keypair = RSA_generate_key(2048, RSA_F4, nullptr, nullptr); // 保存公钥私钥到文件 FILE *pubkey_file = fopen("public.pem", "w"); PEM_write_RSA_PUBKEY(pubkey_file, keypair); fclose(pubkey_file); FILE *privkey_file = fopen("private.pem", "w"); PEM_write_RSAPrivateKey(privkey_file, keypair, nullptr, nullptr, 0, nullptr, nullptr); fclose(privkey_file); // 从文件读取公钥私钥 pubkey_file = fopen("public.pem", "r"); RSA *pubkey = PEM_read_RSA_PUBKEY(pubkey_file, nullptr, nullptr, nullptr); fclose(pubkey_file); privkey_file = fopen("private.pem", "r"); RSA *privkey = PEM_read_RSAPrivateKey(privkey_file, nullptr, nullptr, nullptr); fclose(privkey_file); // 明文数据 const char *plaintext = "Hello, world!"; // 公钥加密 int ciphertext_len = RSA_size(pubkey); unsigned char *ciphertext = new unsigned char[ciphertext_len]; int ret = RSA_public_encrypt(strlen(plaintext), (unsigned char *)plaintext, ciphertext, pubkey, RSA_PKCS1_OAEP_PADDING); if (ret == -1) { printf("RSA_public_encrypt failed!\n"); return -1; } // 私钥解密 unsigned char *decrypted = new unsigned char[ret]; ret = RSA_private_decrypt(ciphertext_len, ciphertext, decrypted, privkey, RSA_PKCS1_OAEP_PADDING); if (ret == -1) { printf("RSA_private_decrypt failed!\n"); return -1; } // 输出解密后的明文 printf("%.*s\n", ret, decrypted); // 释放内存 RSA_free(keypair); RSA_free(pubkey); RSA_free(privkey); delete[] ciphertext; delete[] decrypted; return 0; } ``` 此代码,我们使用 RSA_generate_key 函数生成一个 2048 位的 RSA 密钥对,然后将公钥私钥分别保存到 public.pem 和 private.pem 文件。接着,我们使用 PEM_read_RSA_PUBKEY 和 PEM_read_RSAPrivateKey 函数从文件读取公钥私钥。然后,我们使用 RSA_public_encrypt 函数使用公钥加密明文数据,再使用 RSA_private_decrypt 函数使用私钥解密密文数据。最后,我们输出解密后的明文数据,并释放内存。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值