现代C++新手求助:如何将AES加解密代码拆分到头文件与cpp文件
AES代码拆分到头文件与CPP文件的具体方法
1. 头文件(aes.h)编写
头文件负责声明类结构、成员函数原型和静态常量,必须添加头文件保护避免重复包含:
#pragma once #include <vector> #include <string> class AES { public: enum AESMode { AES_128, AES_192, AES_256 }; explicit AES(AESMode mode = AES_128); ~AES() = default; void setKey(const std::vector<uint8_t>& key); std::vector<uint8_t> encrypt(const std::vector<uint8_t>& plaintext); std::vector<uint8_t> decrypt(const std::vector<uint8_t>& ciphertext); std::string encryptString(const std::string& plaintext); std::string decryptString(const std::string& ciphertext); private: void expandKey(); void addRoundKey(uint8_t round); void subBytes(); void shiftRows(); void mixColumns(); void invSubBytes(); void invShiftRows(); void invMixColumns(); AESMode m_mode; std::vector<uint8_t> m_key; std::vector<uint8_t> m_state; size_t m_numRounds; std::vector<uint8_t> m_expandedKey; static const uint8_t sbox[256]; static const uint8_t invSbox[256]; static const uint8_t rcon[10]; };
2. 实现文件(aes.cpp)编写
cpp文件负责实现头文件中声明的所有成员函数,以及定义类的静态常量:
#include "aes.h" #include <cstring> // 定义静态常量(复制原代码中对应的数组内容) const uint8_t AES::sbox[256] = { 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, // 剩余sbox内容省略,直接用原代码完整数组 }; const uint8_t AES::invSbox[256] = { 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, // 剩余invSbox内容省略,直接用原代码完整数组 }; const uint8_t AES::rcon[10] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36 }; // 构造函数实现 AES::AES(AESMode mode) : m_mode(mode) { switch(mode) { case AES_128: m_numRounds = 10; break; case AES_192: m_numRounds = 12; break; case AES_256: m_numRounds = 14; break; } } // setKey函数实现 void AES::setKey(const std::vector<uint8_t>& key) { m_key = key; expandKey(); } // encrypt函数实现(直接复制原代码中encrypt函数的逻辑) std::vector<uint8_t> AES::encrypt(const std::vector<uint8_t>& plaintext) { // 原代码中encrypt的完整逻辑 } // decrypt函数实现(直接复制原代码中decrypt函数的逻辑) std::vector<uint8_t> AES::decrypt(const std::vector<uint8_t>& ciphertext) { // 原代码中decrypt的完整逻辑 } // 剩余成员函数(expandKey、addRoundKey等)依次复制原代码中的实现逻辑
3. 关键注意事项
- 头文件保护:必须添加
#pragma once或#ifndef AES_H #define AES_H ... #endif,避免重复包含导致编译错误。 - 静态成员变量:类中声明的静态常量(如
sbox、invSbox)必须在cpp文件中定义,不能仅在头文件声明。 - 依赖头文件:确保cpp文件包含所有必要的依赖头文件(如
<cstring>),原代码中用到的工具函数也需放在cpp文件中或封装到类内。 - 编译链接:编译时需同时包含
aes.h和aes.cpp,比如使用g++ main.cpp aes.cpp -o aes_demo命令。
内容的提问来源于stack exchange,提问作者Conkel Conkel
相关产品推荐
相关产品推荐

