C++ 密码学:从理论到加密与哈希实践
密码学是现代应用程序安全的基础。在 C++ 中,开发者可以使用强大的库来实现对称/非对称加密以及密码学哈希。本文将介绍两个关键库:OpenSSL(事实标准)和 Crypto++(纯 C++,易于集成)。您将学习如何加密数据、验证完整性以及保护密码。
基本密码学概念
在进入代码之前,理解三个基本操作很重要:
- 对称加密(AES、ChaCha20)——使用同一个密钥进行加密和解密。速度快,适用于大量数据。
- 非对称加密(RSA、ECC)——使用一对密钥(公钥/私钥)。用于密钥交换和数字签名。
- 哈希(SHA-256、MD5)——将数据不可逆地转换为固定长度的字符串。用于完整性验证和密码存储。
1. 在 C++ 中使用 OpenSSL
OpenSSL 是一个用 C 编写的跨平台库,通过链接使用。安装:sudo apt install libssl-dev(Linux)或通过 vcpkg/conan(Windows)。
示例:AES-256-CBC 对称加密
#include <iostream>#include <string>#include <openssl/evp.h>#include <openssl/rand.h>
std::string aes_encrypt(const std::string& plaintext, const unsigned char* key, const unsigned char* iv) { EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, key, iv);
std::string ciphertext(plaintext.size() + 16, '\\0'); int len = 0, ciphertext_len = 0; EVP_EncryptUpdate(ctx, reinterpret_cast<unsigned char*>(&ciphertext[0]), &len, reinterpret_cast<const unsigned char*>(plaintext.data()), plaintext.size()); ciphertext_len = len; EVP_EncryptFinal_ex(ctx, reinterpret_cast<unsigned char*>(&ciphertext[ciphertext_len]), &len); ciphertext_len += len; ciphertext.resize(ciphertext_len); EVP_CIPHER_CTX_free(ctx); return ciphertext;}
int main() { unsigned char key[32], iv[16]; RAND_bytes(key, sizeof(key)); // 生成随机密钥 RAND_bytes(iv, sizeof(iv));
std::string data = "秘密消息"; std::string encrypted = aes_encrypt(data, key, iv); std::cout << "已加密: " << encrypted.size() << " 字节" << std::endl; return 0;}通过 OpenSSL 进行 SHA-256 哈希
#include <iostream>#include <openssl/sha.h>
std::string sha256(const std::string& str) { unsigned char hash[SHA256_DIGEST_LENGTH]; SHA256_CTX sha256; SHA256_Init(&sha256); SHA256_Update(&sha256, str.c_str(), str.size()); SHA256_Final(hash, &sha256);
std::string output; for(int i = 0; i < SHA256_DIGEST_LENGTH; i++) { char buf[3]; sprintf(buf, "%02x", hash[i]); output += buf; } return output;}
int main() { std::cout << "SHA-256: " << sha256("Hello, Crypto!") << std::endl; return 0;}2. Crypto++ 库(纯 C++ 实现)
Crypto++ (cryptopp) 是一个功能完整的 C++ 库,无外部依赖。安装:sudo apt install libcrypto++-dev 或从 cryptopp.com 下载。
示例:使用 Crypto++ 进行 RSA 加密
#include <iostream>#include <string>#include <cryptopp/rsa.h>#include <cryptopp/osrng.h>#include <cryptopp/base64.h>
int main() { using namespace CryptoPP;
AutoSeededRandomPool rng; Inve