一個RSA的C++封裝

使用RSA的難點:

  1. 公鑰和私鑰的保存與加載。
    在很多的場合下,密鑰是以文件的形式分開保存的,對程序員使用者來說,需要解決公鑰和私鑰的生成、保存、加載問題。
  2. 加解密過程中的分組問題。
    RSA加解密的開銷很大,比DES和AES高2個數量級,一般情況下不適合用來對較長的數據進行加解密。但是,RSA本身也是一種分組加密算法,即使再短的數據加密需求,從程序的健狀性考慮,我們也必須搞清楚和實現分組的加解密支持。

下面的C++可複用代碼,解決了上面的這兩個問題,有需要的朋友可以借鑑。代碼如下:

頭文件RSA.h:

#ifndef __DAKUANG_RSA_H__
#define __DAKUANG_RSA_H__

#include <string>

namespace dakuang
{

    class CRSA
    {
    public:

        // 生成密鑰對,輸出爲PEM文件
        static bool genKeyFiles(const std::string& strPrivateKeyPEMFile, const std::string& strPublicKeyPEMFile);

        // 生成密鑰對,輸出爲PEM字符串
        static bool genKeyStrings(std::string& strPrivateKeyPEMString, std::string& strPublicKeyPEMString);


        // 使用PEM私鑰文件加密
        static bool encryptByPrivatePEMFile(const std::string& strIn, std::string& strOut, const std::string& strKeyPEMFile);

        // 使用PEM私鑰文件解密
        static bool decryptByPrivatePEMFile(const std::string& strIn, std::string& strOut, const std::string& strKeyPEMFile);

        // 使用PEM公鑰文件加密
        static bool encryptByPublicPEMFile(const std::string& strIn, std::string& strOut, const std::string& strKeyPEMFile);

        // 使用PEM公鑰文件解密
        static bool decryptByPublicPEMFile(const std::string& strIn, std::string& strOut, const std::string& strKeyPEMFile);


        // 使用PEM私鑰字符串加密
        static bool encryptByPrivatePEMString(const std::string& strIn, std::string& strOut, const std::string& strKeyPEMString);

        // 使用PEM私鑰字符串解密
        static bool decryptByPrivatePEMString(const std::string& strIn, std::string& strOut, const std::string& strKeyPEMString);

        // 使用PEM公鑰字符串加密
        static bool encryptByPublicPEMString(const std::string& strIn, std::string& strOut, const std::string& strKeyPEMString);

        // 使用PEM公鑰字符串解密
        static bool decryptByPublicPEMString(const std::string& strIn, std::string& strOut, const std::string& strKeyPEMString);

    private:

        // 生成RSA密鑰結構
        static void* __genKey(int nBits);

        // 使用RSA執行加密或解密
        static bool __encryptOrDecrypt(const std::string& strIn, std::string& strOut, const void* pRSA, const void* pFunc, bool bEncrypt);
    };

}

#endif

實現文件RSA.cpp:

#include "RSA.h"

#include <openssl/rsa.h>
#include <openssl/pem.h>

using namespace dakuang;

// 加解密函數簽名
typedef int (*RSA_encryptOrDecrypt)(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding);

// 生成密鑰對,輸出爲PEM文件
bool CRSA::genKeyFiles(const std::string& strPrivateKeyPEMFile, const std::string& strPublicKeyPEMFile)
{
    // 生成RSA
    RSA* rsa = (RSA*)__genKey(1024);
    if (rsa == NULL)
        return false;

    // 輸出私鑰
    {
        BIO* bio = BIO_new_file(strPrivateKeyPEMFile.data(), "w");
        int ret = PEM_write_bio_RSAPrivateKey(bio, rsa, NULL, NULL, 0, NULL, NULL);
        if (ret != 1)
        {
            BIO_free(bio);
            RSA_free(rsa);
            return false;
        }

        BIO_free(bio);
    }

    // 輸出公鑰
    {
        BIO* bio = BIO_new_file(strPublicKeyPEMFile.data(), "w");
        int ret = PEM_write_bio_RSAPublicKey(bio, rsa);
        if (ret != 1)
        {
            BIO_free(bio);
            RSA_free(rsa);
            return false;
        }

        BIO_free(bio);
    }

    RSA_free(rsa);
    return true;
}

// 生成密鑰對,輸出爲PEM字符串
bool CRSA::genKeyStrings(std::string& strPrivateKeyPEMString, std::string& strPublicKeyPEMString)
{
    // 生成RSA
    RSA* rsa = (RSA*)__genKey(1024);
    if (rsa == NULL)
        return false;

    // 輸出私鑰
    {
        BIO* bio = BIO_new(BIO_s_mem());
        int ret = PEM_write_bio_RSAPrivateKey(bio, rsa, NULL, NULL, 0, NULL, NULL);
        if (ret != 1)
        {
            BIO_free(bio);
            RSA_free(rsa);
            return false;
        }

        char sBuf[1024] = {0};
        int bytes = BIO_read(bio, sBuf, 1024);
        if (bytes <= 0)
        {
            BIO_free(bio);
            RSA_free(rsa);
            return false;
        }

        BIO_free(bio);
        strPrivateKeyPEMString.assign(sBuf, bytes);
    }

    // 輸出公鑰
    {
        BIO* bio = BIO_new(BIO_s_mem());
        int ret = PEM_write_bio_RSAPublicKey(bio, rsa);
        if (ret != 1)
        {
            BIO_free(bio);
            RSA_free(rsa);
            return false;
        }

        char sBuf[1024] = {0};
        int bytes = BIO_read(bio, sBuf, 1024);
        if (bytes <= 0)
        {
            BIO_free(bio);
            RSA_free(rsa);
            return false;
        }

        BIO_free(bio);
        strPublicKeyPEMString.assign(sBuf, bytes);
    }

    RSA_free(rsa);
    return true;
}


// 使用PEM私鑰文件加密
bool CRSA::encryptByPrivatePEMFile(const std::string& strIn, std::string& strOut, const std::string& strKeyPEMFile)
{
    // 加載私鑰
    BIO* bio = BIO_new_file(strKeyPEMFile.data(), "r");
    RSA* rsa = PEM_read_bio_RSAPrivateKey(bio, NULL, NULL, NULL);
    BIO_free(bio);

    if (rsa == NULL)
        return false;

    // 使用私鑰加密
    bool b = __encryptOrDecrypt(strIn, strOut, rsa, (const void*)RSA_private_encrypt, true);
    RSA_free(rsa);
    return b;
}

// 使用PEM私鑰文件解密
bool CRSA::decryptByPrivatePEMFile(const std::string& strIn, std::string& strOut, const std::string& strKeyPEMFile)
{
    // 加載私鑰
    BIO* bio = BIO_new_file(strKeyPEMFile.data(), "r");
    RSA* rsa = PEM_read_bio_RSAPrivateKey(bio, NULL, NULL, NULL);
    BIO_free(bio);

    if (rsa == NULL)
        return false;

    // 檢查密文大小是否爲分組的整數倍
    int keySize = RSA_size(rsa);
    int blockSize = keySize;
    if ( (strIn.size() % blockSize) != 0 )
        return false;

    // 使用私鑰解密
    bool b = __encryptOrDecrypt(strIn, strOut, rsa, (const void*)RSA_private_decrypt, false);
    RSA_free(rsa);
    return b;
}

// 使用PEM公鑰文件加密
bool CRSA::encryptByPublicPEMFile(const std::string& strIn, std::string& strOut, const std::string& strKeyPEMFile)
{
    // 加載公鑰
    BIO* bio = BIO_new_file(strKeyPEMFile.data(), "r");
    RSA* rsa = PEM_read_bio_RSAPublicKey(bio, NULL, NULL, NULL);
    BIO_free(bio);

    if (rsa == NULL)
        return false;

    // 使用公鑰加密
    bool b = __encryptOrDecrypt(strIn, strOut, rsa, (const void*)RSA_public_encrypt, true);
    RSA_free(rsa);
    return b;
}

// 使用PEM公鑰文件解密
bool CRSA::decryptByPublicPEMFile(const std::string& strIn, std::string& strOut, const std::string& strKeyPEMFile)
{
    // 加載公鑰
    BIO* bio = BIO_new_file(strKeyPEMFile.data(), "r");
    RSA* rsa = PEM_read_bio_RSAPublicKey(bio, NULL, NULL, NULL);
    BIO_free(bio);

    if (rsa == NULL)
        return false;

    // 檢查密文大小是否爲分組的整數倍
    int keySize = RSA_size(rsa);
    int blockSize = keySize;
    if ( (strIn.size() % blockSize) != 0 )
        return false;

    // 使用公鑰解密
    bool b = __encryptOrDecrypt(strIn, strOut, rsa, (const void*)RSA_public_decrypt, false);
    RSA_free(rsa);
    return b;
}


// 使用PEM私鑰字符串加密
bool CRSA::encryptByPrivatePEMString(const std::string& strIn, std::string& strOut, const std::string& strKeyPEMString)
{
    // 加載私鑰
    BIO* bio = BIO_new_mem_buf((const void*)strKeyPEMString.data(), strKeyPEMString.size());
    RSA* rsa = PEM_read_bio_RSAPrivateKey(bio, NULL, NULL, NULL);
    BIO_free(bio);

    if (rsa == NULL)
        return false;

    // 使用私鑰加密
    bool b = __encryptOrDecrypt(strIn, strOut, rsa, (const void*)RSA_private_encrypt, true);
    RSA_free(rsa);
    return b;
}

// 使用PEM私鑰字符串解密
bool CRSA::decryptByPrivatePEMString(const std::string& strIn, std::string& strOut, const std::string& strKeyPEMString)
{
    // 加載私鑰
    BIO* bio = BIO_new_mem_buf((const void*)strKeyPEMString.data(), strKeyPEMString.size());
    RSA* rsa = PEM_read_bio_RSAPrivateKey(bio, NULL, NULL, NULL);
    BIO_free(bio);

    if (rsa == NULL)
        return false;

    // 檢查密文大小是否爲分組的整數倍
    int keySize = RSA_size(rsa);
    int blockSize = keySize;
    if ( (strIn.size() % blockSize) != 0 )
        return false;

    // 使用私鑰解密
    bool b = __encryptOrDecrypt(strIn, strOut, rsa, (const void*)RSA_private_decrypt, false);
    RSA_free(rsa);
    return b;
}

// 使用PEM公鑰字符串加密
bool CRSA::encryptByPublicPEMString(const std::string& strIn, std::string& strOut, const std::string& strKeyPEMString)
{
    // 加載公鑰
    BIO* bio = BIO_new_mem_buf((const void*)strKeyPEMString.data(), strKeyPEMString.size());
    RSA* rsa = PEM_read_bio_RSAPublicKey(bio, NULL, NULL, NULL);
    BIO_free(bio);

    if (rsa == NULL)
        return false;

    // 使用公鑰加密
    bool b = __encryptOrDecrypt(strIn, strOut, rsa, (const void*)RSA_public_encrypt, true);
    RSA_free(rsa);
    return b;
}

// 使用PEM公鑰字符串解密
bool CRSA::decryptByPublicPEMString(const std::string& strIn, std::string& strOut, const std::string& strKeyPEMString)
{
    // 加載公鑰
    BIO* bio = BIO_new_mem_buf((const void*)strKeyPEMString.data(), strKeyPEMString.size());
    RSA* rsa = PEM_read_bio_RSAPublicKey(bio, NULL, NULL, NULL);
    BIO_free(bio);

    if (rsa == NULL)
        return false;

    // 檢查密文大小是否爲分組的整數倍
    int keySize = RSA_size(rsa);
    int blockSize = keySize;
    if ( (strIn.size() % blockSize) != 0 )
        return false;

    // 使用公鑰解密
    bool b = __encryptOrDecrypt(strIn, strOut, rsa, (const void*)RSA_public_decrypt, false);
    RSA_free(rsa);
    return b;
}

// 生成RSA密鑰結構
void* CRSA::__genKey(int nBits)
{
    RSA* rsa = RSA_new();

    BIGNUM* bne = BN_new();
    BN_set_word(bne, RSA_F4);

    int ret = RSA_generate_key_ex(rsa, nBits, bne, NULL);

    BN_free(bne);

    if (ret != 1)
    {
        RSA_free(rsa);
        return NULL;
    }

    return (void*)rsa;
}

// 使用RSA執行加密或解密
bool CRSA::__encryptOrDecrypt(const std::string& strIn, std::string& strOut, const void* pRSA, const void* pFunc, bool bEncrypt)
{
    const RSA_encryptOrDecrypt encryptOrDecrypt = (const RSA_encryptOrDecrypt)pFunc;

    // 計算加密塊大小
    int nKeySize = RSA_size((RSA*)pRSA);
    int nBlockSize = bEncrypt ? (nKeySize - RSA_PKCS1_PADDING_SIZE) : nKeySize;

    const unsigned char* pIn = (const unsigned char*)strIn.data();
    int nInSize = strIn.size();

    unsigned char* pBuf = new unsigned char[nKeySize];

    // 分組迭代加密
    for (int i = 0; i < nInSize; )
    {
        int nBlockLen = (nInSize - i > nBlockSize ? nBlockSize : nInSize - i);

        int ret = encryptOrDecrypt(nBlockLen, pIn + i, pBuf, (RSA*)pRSA, RSA_PKCS1_PADDING);
        if (ret <= 0)
        {
            delete[] pBuf;
            return false;
        }

        strOut.append((char*)pBuf, ret);
        i += nBlockLen;
    }

    delete[] pBuf;
    return true;
}

使用舉例:

下面的代碼完整地演示了RSA封裝的所有功能,包括PEM文件的生成與加載、字符串密鑰的生成與加載,以及兩種密鑰方法的加解密。

#include <stdio.h>
#include <stdlib.h>

#include "RSA.h"

int main(int argc, char* argv[])
{
    using namespace dakuang;

    std::string strText = "abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567
890abcdefghijklmnopqrstuvwxyz1234567890";

    {
        bool b = CRSA::genKeyFiles("test.key", "test.pub");
        printf("CRSA::genKeyFiles() ret:[%d] \n", b);

        std::string strCipher = "";
        b = CRSA::encryptByPrivatePEMFile(strText, strCipher, "test.key");
        printf("CRSA::encryptByPrivatePEMFile() ret:[%d] cipher len:[%d] \n", b, strCipher.size());

        std::string strText2 = "";
        b = CRSA::decryptByPublicPEMFile(strCipher, strText2, "test.pub");
        printf("CRSA::decryptByPublicPEMFile() ret:[%d] text len:[%d] body:[%s] \n", b, strText2.size(), strText2.data());

        strCipher = "";
        b = CRSA::encryptByPublicPEMFile(strText, strCipher, "test.pub");
        printf("CRSA::encryptByPublicPEMFile() ret:[%d] cipher len:[%d] \n", b, strCipher.size());

        strText2 = "";
        b = CRSA::decryptByPrivatePEMFile(strCipher, strText2, "test.key");
        printf("CRSA::decryptByPrivatePEMFile() ret:[%d] text len:[%d] body:[%s] \n", b, strText2.size(), strText2.data());
    }

    {
        std::string strPrivateKey = "", strPublicKey = "";
        bool b = CRSA::genKeyStrings(strPrivateKey, strPublicKey);
        printf("CRSA::genKeyStrings() ret:[%d] \n", b);

        std::string strCipher = "";
        b = CRSA::encryptByPrivatePEMString(strText, strCipher, strPrivateKey);
        printf("CRSA::encryptByPrivatePEMString() ret:[%d] cipher len:[%d] \n", b, strCipher.size());

        std::string strText2 = "";
        b = CRSA::decryptByPublicPEMString(strCipher, strText2, strPublicKey);
        printf("CRSA::decryptByPublicPEMString() ret:[%d] text len:[%d] body:[%s] \n", b, strText2.size(), strText2.data());

        strCipher = "";
        b = CRSA::encryptByPublicPEMString(strText, strCipher, strPublicKey);
        printf("CRSA::encryptByPublicPEMString() ret:[%d] cipher len:[%d] \n", b, strCipher.size());

        strText2 = "";
        b = CRSA::decryptByPrivatePEMString(strCipher, strText2, strPrivateKey);
        printf("CRSA::decryptByPrivatePEMString() ret:[%d] text len:[%d] body:[%s] \n", b, strText2.size(), strText2.data());
    }

    return 0;
}

生成私鑰內容如下:
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQDqpNkFqAdedWhOc+lukwCKFNamFr0HMSGgjONUE7dYL5wxk2Pe
5QsLIjqgA7dE14AFCQgF5WOyyUdP94xRGZdstH7CCWz2KhG7nX6ZupKwc5mMO+d3
8tpSp98TTx+CWLL/ntpZNB0cwU/Cx9TbkW+Ysto3LyPkjmlh4othcRMbJwIDAQAB
AoGAUV+qA9Qp+hAthEeehMJmRXzElAT+uSfIya0SiW3s/6BDQs4irIIyOkI8opGn
VTCHLTfcmG7dDHvRR2JKPzXo1RgQW7CgBK3/G5u7CCjF43XtdBd7F4f04yE+bOnY
3oGiXyv2N8okL3MtjSbQwsMX//v+M+fcQtVOO1iUtZPcnQECQQD8t1Dl1isvkaET
ZA+kdnzcF50Y0UQ3lIeTZKNhBH27jzs9tg172s/opS0Ef5c99gFx72Wt9QJfZKLu
4ZDHhJzxAkEA7bFpvS7tbCzqNYGrp3pocWGP7R7dGjKnxzy7tXOucPnyiLqlSL/N
48iWb0jneGN6u+/GiHrnwLaGGzh6gvcZlwJAJS4rPsVVsTfxxNKR4pZ0JEVtHXuc
V7kIgUzrJJjujquyAZBJR5GXyRiUGPdUnw8Ug1i/UuqbIMHDnvWcwV3nYQJAe1lo
QC8MMukUGfRS+jTB4qT4pdswbpn/C5vu5XlE+4gaXu5NO/WdiSndN58j0Av/82u5
IbZ2ckHGUnX6zeAhvQJBAJQs5GMT2MCQ8n5cFP/1eT0fiGPeP6qLO0UZ1BTFfGIq
mXz1ITOTo+PbE93uHDf3u299I70zF8v5R3ifFsGmAus=
-----END RSA PRIVATE KEY-----

生成公鑰內容如下:
-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBAOqk2QWoB151aE5z6W6TAIoU1qYWvQcxIaCM41QTt1gvnDGTY97lCwsi
OqADt0TXgAUJCAXlY7LJR0/3jFEZl2y0fsIJbPYqEbudfpm6krBzmYw753fy2lKn
3xNPH4JYsv+e2lk0HRzBT8LH1NuRb5iy2jcvI+SOaWHii2FxExsnAgMBAAE=
-----END RSA PUBLIC KEY-----

輸出:
CRSA::genKeyFiles() ret:[1]
CRSA::encryptByPrivatePEMFile() ret:[1] cipher len:[256]
CRSA::decryptByPublicPEMFile() ret:[1] text len:[144] body:[abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890]
CRSA::encryptByPublicPEMFile() ret:[1] cipher len:[256]
CRSA::decryptByPrivatePEMFile() ret:[1] text len:[144] body:[abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890]
CRSA::genKeyStrings() ret:[1]
CRSA::encryptByPrivatePEMString() ret:[1] cipher len:[256]
CRSA::decryptByPublicPEMString() ret:[1] text len:[144] body:[abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890]
CRSA::encryptByPublicPEMString() ret:[1] cipher len:[256]
CRSA::decryptByPrivatePEMString() ret:[1] text len:[144] body:[abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890]



ref:https://www.jianshu.com/p/947630b33df1

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章