C++中的密码学:加密与哈希——完整指南
密码学是现代应用程序安全的基础。在C++中,开发者可以使用强大的库来实现数据加密、解密和哈希。在本文中,我们将详细介绍两个流行的库:OpenSSL 和 Crypto++,并解析关键概念:对称加密(AES)、非对称加密(RSA)和密码学哈希函数(SHA-256)。
1. 密码学基本概念
在进入代码之前,理解基本术语非常重要:
- 对称加密——使用同一个密钥进行加密和解密。示例:AES、DES、ChaCha20。
- 非对称加密——一对密钥:公钥(用于加密)和私钥(用于解密)。示例:RSA、ECC。
- 哈希函数——将数据不可逆地转换为固定长度的字符串。示例:SHA-256、MD5(已过时)、BLAKE2。
- 盐值(Salt)——在哈希前添加到密码中的随机数据,用于防范彩虹表攻击。
2. C++中的OpenSSL库
OpenSSL是一个开源的跨平台库,实现了SSL/TLS协议和广泛的密码学算法。要在C++中使用它,需要包含头文件并链接libssl和libcrypto库。
示例1:使用OpenSSL进行SHA-256哈希
#include <iostream>#include <openssl/sha.h>#include <cstring>
std::string sha256(const std::string& input) { unsigned char hash[SHA256_DIGEST_LENGTH]; SHA256_CTX sha256; SHA256_Init(&sha256); SHA256_Update(&sha256, input.c_str(), input.length()); 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::string data = "PythonLib - C++中的密码学"; std::cout << "SHA-256: " << sha256(data) << std::endl; return 0;}此代码演示了SHA256上下文的基本使用。函数SHA256_Init初始化上下文,SHA256_Update添加数据(可多次调用以进行流式处理),而SHA256_Final完成计算并写入结果。
示例2:AES-256-CBC对称加密
#include <iostream>#include <openssl/evp.h>#include <vector>#include <cstring>
std::vector<unsigned char> 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::vector<unsigned char> ciphertext(plaintext.size() + EVP_CIPHER_block_size(EVP_aes_256_cbc())); int len = 0; int ciphertext_len = 0;
EVP_EncryptUpdate(ctx, ciphertext.data(), &len, reinterpret_cast<const unsigned char*>(plaintext.c_str()), plaintext.size()); ciphertext_len = len;
EVP_EncryptFinal_ex(ctx, ciphertext.data() + len, &len); ciphertext_len += len; ciphertext.resize(ciphertext_len);
EVP_CIPHER_CTX_free(ctx); return ciphertext;}
int main() { // 256位密钥(32字节)和128位IV(16字节) unsigned char key[32] = "01234567890123456789012345678901"; unsigned char iv[16] = "0123456789012345";
std::string message = "PythonLib的机密数据";