当前位置:首页 > C++ > 正文

C++语言AES加密实现(手把手教你用C++完成AES加解密,小白也能轻松上手)

在现代软件开发中,数据安全至关重要。而AES(Advanced Encryption Standard)作为目前最广泛使用的对称加密算法之一,因其高效性和安全性被大量应用于各类系统中。本文将围绕C++ AES加密这一主题,详细讲解如何在C++项目中实现AES加解密功能,即使你是编程新手,也能一步步跟着操作成功!

C++语言AES加密实现(手把手教你用C++完成AES加解密,小白也能轻松上手) C++ AES加密 AES加密实现 C++加密教程 小白学AES 第1张

什么是AES加密?

AES是一种对称加密算法,意味着加密和解密使用相同的密钥。它支持128位、192位和256位三种密钥长度,其中128位最为常用。由于其速度快、安全性高,被广泛用于文件加密、网络通信、数据库保护等场景。

为什么选择C++实现AES?

C++是一门高性能的编程语言,适合开发对性能要求高的安全模块。通过在C++中集成AES加密,你可以构建更安全、更高效的本地应用或服务端程序。这也是许多开发者学习C++加密教程的重要原因。

准备工作:安装OpenSSL库

C++标准库本身不包含AES实现,因此我们需要借助第三方库。这里推荐使用广泛支持且稳定的 OpenSSL 库。

Windows用户可通过 vcpkg 或直接下载预编译库;Linux/macOS用户可使用包管理器安装:

# Ubuntu/Debiansudo apt-get install libssl-dev# macOS (使用 Homebrew)brew install openssl

C++ AES加密完整代码示例

下面是一个完整的C++程序,使用OpenSSL实现AES-128-CBC模式的加密与解密。我们将使用PKCS7填充方式处理明文长度不足的情况。

#include <iostream>#include <string>#include <vector>#include <openssl/aes.h>#include <openssl/evp.h>// AES-128-CBC 加密函数std::vector<unsigned char> aes_encrypt(const std::string& plaintext, const std::string& key) {    EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();    if (!ctx) return {};    // 初始化加密上下文(使用AES-128-CBC)    if (EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), nullptr,                           reinterpret_cast<const unsigned char*>(key.data()),                           reinterpret_cast<const unsigned char*>(key.data()))) {        std::vector<unsigned char> ciphertext(plaintext.size() + AES_BLOCK_SIZE);        int len = 0, ciphertext_len = 0;        // 执行加密        if (EVP_EncryptUpdate(ctx,                              ciphertext.data(), &len,                              reinterpret_cast<const unsigned char*>(plaintext.data()),                              static_cast<int>(plaintext.size()))) {            ciphertext_len = len;            // 完成加密(处理填充)            if (EVP_EncryptFinal_ex(ctx, ciphertext.data() + len, &len)) {                ciphertext_len += len;                ciphertext.resize(ciphertext_len);                EVP_CIPHER_CTX_free(ctx);                return ciphertext;            }        }    }    EVP_CIPHER_CTX_free(ctx);    return {};}// AES-128-CBC 解密函数std::string aes_decrypt(const std::vector<unsigned char>& ciphertext, const std::string& key) {    EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();    if (!ctx) return "";    if (EVP_DecryptInit_ex(ctx, EVP_aes_128_cbc(), nullptr,                           reinterpret_cast<const unsigned char*>(key.data()),                           reinterpret_cast<const unsigned char*>(key.data()))) {        std::vector<unsigned char> plaintext(ciphertext.size());        int len = 0, plaintext_len = 0;        if (EVP_DecryptUpdate(ctx,                              plaintext.data(), &len,                              ciphertext.data(),                              static_cast<int>(ciphertext.size()))) {            plaintext_len = len;            if (EVP_DecryptFinal_ex(ctx, plaintext.data() + len, &len)) {                plaintext_len += len;                EVP_CIPHER_CTX_free(ctx);                return std::string(reinterpret_cast<char*>(plaintext.data()), plaintext_len);            }        }    }    EVP_CIPHER_CTX_free(ctx);    return "";}int main() {    std::string plaintext = "Hello, this is a secret message!";    std::string key = "0123456789abcdef"; // 必须为16字节(AES-128)    std::cout << "原始明文: " << plaintext << std::endl;    auto encrypted = aes_encrypt(plaintext, key);    std::cout << "加密后(十六进制): ";    for (auto& b : encrypted) {        printf("%02x", b);    }    std::cout << std::endl;    std::string decrypted = aes_decrypt(encrypted, key);    std::cout << "解密后明文: " << decrypted << std::endl;    return 0;}

编译与运行

将上述代码保存为 aes_demo.cpp,然后使用以下命令编译(需链接OpenSSL库):

g++ -o aes_demo aes_demo.cpp -lssl -lcrypto

运行程序后,你将看到类似如下输出:

原始明文: Hello, this is a secret message!加密后(十六进制): a3f1c8d9e0b2a4f6...解密后明文: Hello, this is a secret message!

注意事项与安全建议

  • 密钥管理:不要将密钥硬编码在源码中,应从安全配置文件或环境变量读取。
  • IV(初始化向量):本例中为简化使用了密钥作为IV,实际应用中应使用随机IV并随密文一起存储。
  • 模式选择:CBC模式需要填充,而GCM模式支持认证加密,更适合网络传输。
  • OpenSSL版本:确保使用最新版OpenSSL以避免已知漏洞。

结语

通过本教程,你已经掌握了如何在C++中使用OpenSSL实现AES加密与解密。无论你是开发桌面软件、嵌入式系统还是服务器程序,这项技能都能帮助你提升数据安全性。希望这篇小白学AES的指南对你有所帮助!

如果你觉得有用,欢迎收藏本教程,并尝试将其集成到你的项目中。记住,安全无小事,正确使用加密技术是每个开发者的基本功!