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 私加公解

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM