RSA加解密 公钥加密私钥解密 公加私解 && C++ 调用openssl库 的代码实例

前提:秘钥长度=1024

==============================================

    对一片(117字节)明文加密

==============================================

// 公钥加密    
std::string rsa_pub_encrypt(const std::string &clearText,  std::string &pubKey)  
{  
    std::string strRet;  
    BIO *keybio = BIO_new_mem_buf((unsigned char *)pubKey.c_str(), -1);  
    //keybio = BIO_new_mem_buf((unsigned char *)strPublicKey.c_str(), -1);  
    // 此处有三种方法  
    // 1, 读取内存里生成的密钥对,再从内存生成rsa  
    // 2, 读取磁盘里生成的密钥对文本文件,在从内存生成rsa  
    // 3,直接从读取文件指针生成rsa  
    //RSA* pRSAPublicKey = RSA_new();  
    RSA* rsa = RSA_new();
    rsa = PEM_read_bio_RSAPublicKey(keybio, &rsa, NULL, NULL);
    if (!rsa)
    {
            BIO_free_all(keybio);
            return std::string("");
    }

    int len = RSA_size(rsa);  
    //int len = 1028;
    char *encryptedText = (char *)malloc(len + 1);  
    memset(encryptedText, 0, len + 1);  

    // 加密函数  
    int ret = RSA_public_encrypt(clearText.length(), (const unsigned char*)clearText.c_str(), (unsigned char*)encryptedText, rsa, RSA_PKCS1_PADDING);  
    if (ret >= 0)  
        strRet = std::string(encryptedText, ret);  

    // 释放内存  
    free(encryptedText);  
    BIO_free_all(keybio);  
    RSA_free(rsa);

    return strRet;  
}  

==============================================

    对一片(128字节)密文解密

==============================================

// 私钥解密    
std::string rsa_pri_decrypt(const std::string &cipherText, const std::string &priKey)  
{  
    std::string strRet;  
    RSA *rsa = RSA_new();  
    BIO *keybio;  
    keybio = BIO_new_mem_buf((unsigned char *)priKey.c_str(), -1);  

    // 此处有三种方法  
    // 1, 读取内存里生成的密钥对,再从内存生成rsa  
    // 2, 读取磁盘里生成的密钥对文本文件,在从内存生成rsa  
    // 3,直接从读取文件指针生成rsa  
    rsa = PEM_read_bio_RSAPrivateKey(keybio, &rsa, NULL, NULL);  

    int len = RSA_size(rsa);  
    char *decryptedText = (char *)malloc(len + 1);  
    memset(decryptedText, 0, len + 1);  

    // 解密函数  
    int ret = RSA_private_decrypt(cipherText.length(), (const unsigned char*)cipherText.c_str(), (unsigned char*)decryptedText, rsa, RSA_PKCS1_PADDING);  
    if (ret >= 0)  
        strRet = std::string(decryptedText, ret);  

    // 释放内存  
    free(decryptedText);  
    BIO_free_all(keybio);  
    RSA_free(rsa);  

    return strRet;  
}  

 

 

注:工作中只用到了 rsa私加公解,因此没有 针对全部明文的公加私解的代码实现,请参考附录。

附:rsa 私加公解

 

原文链接: https://www.cnblogs.com/azbane/p/10180422.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    RSA加解密  公钥加密私钥解密  公加私解  && C++ 调用openssl库 的代码实例

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/398670

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月12日 上午9:46
下一篇 2023年4月12日 上午9:46

相关推荐