RSA算法(C++)

RSA加解密过程

RSA为非对称加密算法,由一对公钥和一对私钥构成,私钥加密公钥解密,公钥加密私钥解密
如下图,D为私密的,假设传输英文字母,我们给英文字母编号A=1,B=2,C=3…
在这里插入图片描述

RSA加解密过程

两对密钥产生方法如下
在这里插入图片描述

C++ OpenSSL库实现加解密

#include <openssl/rsa.h> // 包含OpenSSL RSA加密算法相关函数
#include <openssl/pem.h> // 包含PEM格式编码和解码函数
#include <openssl/err.h> // 包含错误处理函数
#include <iostream>      // 包含标准输入输出流
#include <cstring>       // 包含C字符串处理函数
#include <vector>        // 包含向量容器
#include <memory>        // 包含智能指针
#include <stdexcept>     // 包含标准异常类

// RSAEncryptor类用于封装RSA加密和解密操作
class RSAEncryptor
{
private:
    // 使用智能指针管理RSA结构体和BIGNUM结构体资源
    std::unique_ptr<RSA, decltype(&RSA_free)> rsa;
    std::unique_ptr<BIGNUM, decltype(&BN_free)> bn;

public:
    // 构造函数,初始化RSA密钥对
    RSAEncryptor() : rsa(RSA_new(), RSA_free), bn(BN_new(), BN_free)
    {
        // 设置公钥指数为RSA_F4(65537),这是一个常用的公钥指数
        BN_set_word(bn.get(), RSA_F4);
        // 生成2048位的RSA密钥对
        if (RSA_generate_key_ex(rsa.get(), 2048, bn.get(), nullptr) != 1)
        {
            // 如果密钥生成失败,抛出异常
            throw std::runtime_error("RSA key generation failed");
        }
    }

    // 析构函数,默认即可,智能指针会自动释放资源

    // 加密函数,接收一个字符串,返回加密后的字节数组
    std::vector<unsigned char> encrypt(const std::string &plaintext)
    {
        // 获取RSA密钥长度
        int rsa_size = RSA_size(rsa.get());
        // 创建足够大的缓冲区来存储加密数据
        std::vector<unsigned char> encrypted(rsa_size);
        
        // 执行公钥加密操作
        int result = RSA_public_encrypt(plaintext.size(),
                                        reinterpret_cast<const unsigned char *>(plaintext.data()),
                                        encrypted.data(),
                                        rsa.get(),
                                        RSA_PKCS1_PADDING);
        // 如果加密失败,抛出异常
        if (result == -1)
        {
            throw std::runtime_error("RSA encryption failed");
        }

        // 调整vector大小以匹配加密后的数据长度
        encrypted.resize(result);
        return encrypted;
    }

    // 解密函数,接收加密后的字节数组,返回解密后的字符串
    std::string decrypt(const std::vector<unsigned char> &ciphertext)
    {
        // 获取RSA密钥长度
        int rsa_size = RSA_size(rsa.get());
        // 创建足够大的缓冲区来存储解密数据
        std::vector<unsigned char> decrypted(rsa_size);

        // 执行私钥解密操作
        int result = RSA_private_decrypt(ciphertext.size(),
                                         ciphertext.data(),
                                         decrypted.data(),
                                         rsa.get(),
                                         RSA_PKCS1_PADDING);
        // 如果解密失败,抛出异常
        if (result == -1)
        {
            throw std::runtime_error("RSA decryption failed");
        }

        // 将解密后的数据转换为字符串
        return std::string(decrypted.begin(), decrypted.begin() + result);
    }
};

// 主函数,演示RSAEncryptor类的使用
int main()
{
    try
    {
        // 创建RSAEncryptor实例
        RSAEncryptor encryptor;

        // 原始消息
        std::string original_message = "你好, RSA!";
        // 加密消息
        std::vector<unsigned char> encrypted_message = encryptor.encrypt(original_message);
        // 解密消息
        std::string decrypted_message = encryptor.decrypt(encrypted_message);

        // 输出原始消息
        std::cout << "原信息: " << original_message << std::endl;
        // 输出加密后的数据
        std::cout << "加密数据: ";
        for (auto c : encrypted_message)
        {
            std::cout << std::hex << static_cast<int>(c);
        }
        std::cout << std::endl;
        // 输出解密后的数据
        std::cout << "解密数据: " << decrypted_message << std::endl;
    }
    catch (const std::exception &e)
    {
        // 如果发生异常,输出错误信息
        std::cerr << "发生错误: " << e.what() << std::endl;
        return 1;
    }

    return 0;
}

编译运行:

g++ -o rsa_example RSA.cpp -lssl -lcrypto

运行结果:
在这里插入图片描述

相关推荐

  1. .NET RSA加密算法实现

    2024-07-12 22:14:04       37 阅读
  2. 加密算法RSA非对称加密算法

    2024-07-12 22:14:04       21 阅读
  3. 密码学中的RSA算法与椭圆曲线算法

    2024-07-12 22:14:04       35 阅读
  4. 深入了解RSA算法:公钥密码学的基石

    2024-07-12 22:14:04       36 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 22:14:04       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 22:14:04       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 22:14:04       58 阅读
  4. Python语言-面向对象

    2024-07-12 22:14:04       69 阅读

热门阅读

  1. P3378 【模板】堆 题解

    2024-07-12 22:14:04       21 阅读
  2. Spring源码二十四:Bean流程探讨

    2024-07-12 22:14:04       23 阅读
  3. 信息收集简介

    2024-07-12 22:14:04       19 阅读
  4. 有哪些好用的项目管理工具?

    2024-07-12 22:14:04       21 阅读
  5. 拦截HTTP的多种方式

    2024-07-12 22:14:04       24 阅读
  6. 如何使用这个XMLHttpRequest?

    2024-07-12 22:14:04       20 阅读
  7. OracleLinux6.9升级UEK内核

    2024-07-12 22:14:04       22 阅读
  8. php将png转为jpg,可设置压缩率

    2024-07-12 22:14:04       19 阅读
  9. XML标记语言简介

    2024-07-12 22:14:04       16 阅读
  10. C++学习

    C++学习

    2024-07-12 22:14:04      20 阅读
  11. makefile常用规则

    2024-07-12 22:14:04       18 阅读