首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

基於 Crypto++ 庫實作 RSA 簽名與加解密完整範例

     編輯:關於C++

Crypto++ 是功能最全面的 C++ 加密庫,但原始碼龐大(靜態庫高達 34 MB),導出最小化二進位需額外裁剪。本文提供一個可直接編譯的極簡範例,示範 RSA 金鑰對生成、字串加密、解密、簽名/驗簽 的核心流程,適合快速整合至專案。

關鍵類別對照

功能Crypto++ 類別備註
私鑰解密/簽名RSAES_OAEP_SHA_Decryptor / RSASS_PKCS1v15_SHA_SignerOAEP 填充 + SHA-1
公鑰加密/驗簽RSAES_OAEP_SHA_Encryptor / RSASS_PKCS1v15_SHA_Verifier對應之公鑰操作
編碼/解碼HexEncoder / HexDecoder二進位 ↔ 十六進位字串
檔案 I/OFileSource / FileSink管道式串流處理
隨機數源RandomPool / AutoSeededRandomPool現代建議改用後者

完整可編譯範例

#include <cryptopp/rsa.h>
#include <cryptopp/osrng.h>
#include <cryptopp/hex.h>
#include <cryptopp/files.h>
#include <iostream>, <string>

using namespace CryptoPP;

void GenKeys(const char* priFile, const char* pubFile, unsigned int bits=2048) {
    AutoSeededRandomPool rng;
    InvertibleRSAFunction params;
    params.GenerateRandomWithKeySize(rng, bits);
    params.DEREncode(FileSink(priFile).Ref());
    RSAFunction pub(params);
    pub.DEREncode(FileSink(pubFile).Ref());
}

std::string Encrypt(const char* pubFile, const std::string& plain) {
    FileSource fs(pubFile, true, new HexDecoder);
    RSAES_OAEP_SHA_Encryptor encryptor(fs);
    AutoSeededRandomPool rng;
    std::string cipher;
    StringSource(plain, true,
        new PK_EncryptorFilter(rng, encryptor,
            new HexEncoder(new StringSink(cipher))));
    return cipher;
}

std::string Decrypt(const char* priFile, const std::string& cipher) {
    FileSource fs(priFile, true, new HexDecoder);
    RSAES_OAEP_SHA_Decryptor decryptor(fs);
    AutoSeededRandomPool rng;
    std::string plain;
    StringSource(cipher, true,
        new HexDecoder(new PK_DecryptorFilter(rng, decryptor,
            new StringSink(plain))));
    return plain;
}

int main() {
    GenKeys("pri.der", "pub.der", 2048);
    std::string msg = "Hello Crypto++ RSA!";
    std::string enc = Encrypt("pub.der", msg);
    std::string dec = Decrypt("pri.der", enc);
    std::cout << "Original: " << msg << "\nEncrypted: " << enc << "\nDecrypted: " << dec << std::endl;
    return 0;
}

實務部署提醒

  • 金鑰長度:2024 年建議 ≥2048 位元,長期機密建議 3072 或 4096。
  • 填充模式:OAEP 抗選擇密文攻擊,優於 PKCS#1 v1.5。
  • 體積優化:僅編譯 rsa.cpp、oaep.cpp、sha.cpp、hex.cpp、files.cpp 等核心檔,可將靜態庫壓縮至 2~3 MB。
  • 跨平台:Crypto++ 支援 Windows/Linux/macOS/iOS/Android,CMake 專案一鍵建置。
「Crypto++ 功能強大但學習曲線陡峭;掌握『管道式』串流設計(Source → Filter → Sink)是駕馭它的關鍵。」
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved