一、不依賴外部庫實現
使用自定義的XOR加密算法結合簡單的密鑰擴展。
實現說明
這個方案不依賴任何外部庫,僅使用C++標準庫實現:
- 加密原理:采用XOR加密算法,這是一種簡單但有效的對稱加密方式,相同的密鑰可以用于加密和解密
- 密鑰處理:實現了密鑰擴展功能,確保短密碼可以加密任意長度的內容
- 用戶管理:使用簡單的哈希函數存儲密碼(而非明文),支持用戶添加和驗證
- 文件操作:以二進制方式讀寫文件,確保加密數據正確存儲
// markdown_encryptor.h
#include <string>
#include <map>
#include <sstream>
#include <fstream>
#include <cstdint>
class MarkdownEncryptor {
private:// 存儲用戶名和密碼哈希std::map<std::string, std::string> users;// 簡單的哈希函數,用于密碼存儲std::string simpleHash(const std::string& input);// 密鑰擴展,將短密碼擴展為與數據長度匹配的密鑰std::string expandKey(const std::string& password, size_t dataLength);public:// 添加用戶bool addUser(const std::string& username, const std::string& password);// 驗證用戶bool verifyUser(const std::string& username, const std::string& password);// 加密ostringstream中的內容std::string encrypt(const std::ostringstream& markdown, const std::string& password);// 解密內容std::string decrypt(const std::string& encryptedData, const std::string& password);// 保存加密數據到文件bool saveToFile(const std::string& data, const std::string& filename);// 從文件加載加密數據std::string loadFromFile(const std::string& filename);
};// markdown_encryptor.cpp
// 簡單的哈希函數實現
std::string MarkdownEncryptor::simpleHash(const std::string& input) {uint32_t hash = 0x811c9dc5; // 初始化值for (char c : input) {hash ^= static_cast<uint8_t>(c);hash *= 0x01000193; // 質數乘數}// 轉換為十六進制字符串char buffer[9];snprintf(buffer, sizeof(buffer), "%08x", hash);return std::string(buffer);
}// 密鑰擴展函數
std::string MarkdownEncryptor::expandKey(const std::string& password, size_t dataLength) {if (password.empty()) return "";std::string expanded;expanded.reserve(dataLength);size_t keyIndex = 0;for (size_t i = 0; i < dataLength; ++i) {expanded += password[keyIndex];keyIndex = (keyIndex + 1) % password.size();}return expanded;
}// 添加用戶
bool MarkdownEncryptor::addUser(const std::string& username, const std::string& password) {if (users.find(username) != users.end()) {return false; // 用戶已存在}// 存儲哈希后的密碼,而不是明文users[username] = simpleHash(password);return true;
}// 驗證用戶
bool MarkdownEncryptor::verifyUser(const std::string& username, const std::string& password) {auto it = users.find(username);if (it == users.end()) {return false; // 用戶不存在}// 比較哈希值return it->second == simpleHash(password);
}// 加密實現 - 使用XOR算法
std::string MarkdownEncryptor::encrypt(const std::ostringstream& markdown, const std::string& password) {std::string data = markdown.str();if (data.empty() || password.empty()) return "";std::string key = expandKey(password, data.size());std::string encrypted;encrypted.reserve(data.size());// XOR加密for (size_t i = 0; i < data.size(); ++i) {encrypted += data[i] ^ key[i];}return encrypted;
}// 解密實現 - XOR算法解密(與加密相同)
std::string MarkdownEncryptor::decrypt(const std::string& encryptedData, const std::string& password) {if (encryptedData.empty() || password.empty()) return "";std::string key = expandKey(password, encryptedData.size());std::string decrypted;decrypted.reserve(encryptedData.size());// XOR解密(與加密算法相同)for (size_t i = 0; i < encryptedData.size(); ++i) {decrypted += encryptedData[i] ^ key[i];}return decrypted;
}// 保存到文件
bool MarkdownEncryptor::saveToFile(const std::string& data, const std::string& filename, bool append = false) {// 根據append參數選擇打開模式std::ios_base::openmode mode = std::ios::binary;if (append) {mode |= std::ios::app; // 追加模式} else {mode |= std::ios::trunc; // 截斷模式(默認,覆蓋文件)}std::ofstream file(filename, mode);if (!file.is_open()) {return false;}file.write(data.data(), data.size());return true;
}// 從文件加載
std::string MarkdownEncryptor::loadFromFile(const std::string& filename) {std::ifstream file(filename, std::ios::binary | std::ios::ate);if (!file.is_open()) {return "";}std::streamsize size = file.tellg();file.seekg(0, std::ios::beg);std::string data(size, '\0');if (file.read(&data[0], size)) {return data;}return "";
}// main.cpp
int main() {// 創建加密器實例MarkdownEncryptor encryptor;// 添加用戶std::string username = "editor";std::string password = "mySecretPass123";if (encryptor.addUser(username, password)) {std::cout << "用戶 '" << username << "' 創建成功" << std::endl;} else {std::cout << "用戶 '" << username << "' 創建失敗(可能已存在)" << std::endl;return 1;}// 驗證用戶if (encryptor.verifyUser(username, password)) {std::cout << "用戶驗證成功,可以進行加密操作" << std::endl;} else {std::cout << "用戶驗證失敗,無法繼續" << std::endl;return 1;}// 創建Markdown內容std::ostringstream markdown;markdown << "# 項目規劃文檔\n"<< "這是一個需要加密保護的內部文檔。\n\n"<< "## 核心目標\n"<< "- 完成產品迭代\n"<< "- 優化用戶體驗\n"<< "- 提升系統性能\n\n"<< "## 時間節點\n"<< "- 階段一:2025年9月完成\n"<< "- 階段二:2025年11月完成\n";// 加密內容std::string encrypted = encryptor.encrypt(markdown, password);if (encrypted.empty()) {std::cout << "加密失敗" << std::endl;return 1;}// 保存到文件// encryptor.saveToFile(encrypted, "project_plan.enc", true) 追加內容到文件(而不是覆蓋)if (encryptor.saveToFile(encrypted, "project_plan.enc")) {std::cout << "加密文件已保存為 project_plan.enc" << std::endl;} else {std::cout << "保存文件失敗" << std::endl;return 1;}// 從文件加載并解密std::string loadedData = encryptor.loadFromFile("project_plan.enc");if (loadedData.empty()) {std::cout << "加載文件失敗" << std::endl;return 1;}std::string decrypted = encryptor.decrypt(loadedData, password);if (decrypted.empty()) {std::cout << "解密失敗,可能密碼錯誤" << std::endl;return 1;}// 顯示解密后的內容std::cout << "\n解密成功,內容如下:\n" << std::endl;std::cout << decrypted << std::endl;return 0;
}
安全性
這種基礎加密方案適合簡單場景,但安全性不如專業加密算法:
- 優點:實現簡單,無外部依賴,適合快速集成
- 缺點:安全性有限,不適合保護高度敏感信息
使用方法
- 編譯所有文件(無需鏈接額外庫)
- 創建加密器實例并添加用戶
- 驗證用戶后,使用密碼加密文件內容
- 保存加密文件,解密時使用相同密碼
這種實現可以直接嵌入到你的項目中,無需擔心外部依賴問題。
要實現對文本的加密保護并支持用戶密碼功能,我們可以使用AES加密算法結合密碼哈希來實現。下面是一個C++實現方案,使用OpenSSL庫提供加密功能:
二、依賴OpenSSL庫
使用 AES 加密算法結合密碼哈希來實現,OpenSSL 庫提供加密功能
#include <string>
#include <vector>
#include <map>
#include <ostringstream>
#include <openssl/aes.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/sha.h>
#include <fstream>
#include <iostream>// markdown_encryptor.h
class MarkdownEncryptor {
private:// 用戶存儲:用戶名 -> 密碼哈希std::map<std::string, std::string> users;// 鹽值長度static const int SALT_LENGTH = 16;// 密鑰長度 (AES-256)static const int KEY_LENGTH = 32;// IV向量長度static const int IV_LENGTH = 16;// 迭代次數static const int ITERATIONS = 10000;// 從密碼和鹽值生成密鑰std::vector<unsigned char> generateKey(const std::string& password, const unsigned char* salt);// 哈希密碼用于用戶認證std::string hashPassword(const std::string& password, const unsigned char* salt);// 生成隨機鹽值std::vector<unsigned char> generateSalt();public:MarkdownEncryptor() = default;// 添加用戶bool addUser(const std::string& username, const std::string& password);// 驗證用戶密碼bool verifyUser(const std::string& username, const std::string& password);// 加密markdown內容std::string encrypt(const std::ostringstream& markdownContent, const std::string& password);// 解密內容std::string decrypt(const std::string& encryptedData, const std::string& password);// 保存加密數據到文件bool saveToFile(const std::string& encryptedData, const std::string& filename);// 從文件加載加密數據std::string loadFromFile(const std::string& filename);
};// markdown_encryptor.cpp
std::vector<unsigned char> MarkdownEncryptor::generateSalt() {std::vector<unsigned char> salt(SALT_LENGTH);if (RAND_bytes(salt.data(), SALT_LENGTH) != 1) {throw std::runtime_error("Failed to generate salt");}return salt;
}std::vector<unsigned char> MarkdownEncryptor::generateKey(const std::string& password, const unsigned char* salt) {std::vector<unsigned char> key(KEY_LENGTH);if (PKCS5_PBKDF2_HMAC_SHA1(password.c_str(), password.length(),salt, SALT_LENGTH,ITERATIONS, KEY_LENGTH,key.data()) != 1) {throw std::runtime_error("Failed to generate key");}return key;
}std::string MarkdownEncryptor::hashPassword(const std::string& password, const unsigned char* salt) {unsigned char hash[SHA256_DIGEST_LENGTH];std::vector<unsigned char> key = generateKey(password, salt);SHA256(key.data(), key.size(), hash);std::string hashStr;for (int i = 0; i < SHA256_DIGEST_LENGTH; ++i) {char buf[3];sprintf(buf, "%02x", hash[i]);hashStr += buf;}return hashStr;
}bool MarkdownEncryptor::addUser(const std::string& username, const std::string& password) {if (users.find(username) != users.end()) {return false; // 用戶已存在}try {std::vector<unsigned char> salt = generateSalt();std::string saltStr(reinterpret_cast<char*>(salt.data()), salt.size());std::string passwordHash = hashPassword(password, salt.data());// 存儲格式: 鹽值 + 哈希值users[username] = saltStr + passwordHash;return true;} catch (...) {return false;}
}bool MarkdownEncryptor::verifyUser(const std::string& username, const std::string& password) {auto it = users.find(username);if (it == users.end()) {return false; // 用戶不存在}std::string storedData = it->second;if (storedData.length() < SALT_LENGTH) {return false; // 數據無效}// 提取鹽值std::vector<unsigned char> salt(SALT_LENGTH);memcpy(salt.data(), storedData.c_str(), SALT_LENGTH);// 計算哈希并比較std::string passwordHash = hashPassword(password, salt.data());return passwordHash == storedData.substr(SALT_LENGTH);
}std::string MarkdownEncryptor::encrypt(const std::ostringstream& markdownContent, const std::string& password) {try {// 生成鹽值和密鑰std::vector<unsigned char> salt = generateSalt();std::vector<unsigned char> key = generateKey(password, salt.data());// 生成IV向量unsigned char iv[IV_LENGTH];if (RAND_bytes(iv, IV_LENGTH) != 1) {throw std::runtime_error("Failed to generate IV");}// 獲取要加密的數據std::string plaintext = markdownContent.str();// 準備加密上下文EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();if (!ctx) {throw std::runtime_error("Failed to create cipher context");}// 初始化加密操作if (EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, key.data(), iv) != 1) {EVP_CIPHER_CTX_free(ctx);throw std::runtime_error("Failed to initialize encryption");}// 計算加密后的數據長度int ciphertext_len = plaintext.length() + AES_BLOCK_SIZE;std::vector<unsigned char> ciphertext(ciphertext_len);// 執行加密int len;if (EVP_EncryptUpdate(ctx, ciphertext.data(), &len, reinterpret_cast<const unsigned char*>(plaintext.c_str()), plaintext.length()) != 1) {EVP_CIPHER_CTX_free(ctx);throw std::runtime_error("Encryption failed");}ciphertext_len = len;// 完成加密if (EVP_EncryptFinal_ex(ctx, ciphertext.data() + len, &len) != 1) {EVP_CIPHER_CTX_free(ctx);throw std::runtime_error("Final encryption step failed");}ciphertext_len += len;// 釋放上下文EVP_CIPHER_CTX_free(ctx);// 存儲格式: 鹽值 + IV + 密文長度 + 密文std::string result;result.append(reinterpret_cast<char*>(salt.data()), salt.size());result.append(reinterpret_cast<char*>(iv), IV_LENGTH);result.append(reinterpret_cast<char*>(&ciphertext_len), sizeof(int));result.append(reinterpret_cast<char*>(ciphertext.data()), ciphertext_len);return result;} catch (const std::exception& e) {std::cerr << "Encryption error: " << e.what() << std::endl;return "";}
}std::string MarkdownEncryptor::decrypt(const std::string& encryptedData, const std::string& password) {try {// 檢查數據長度是否足夠if (encryptedData.length() < SALT_LENGTH + IV_LENGTH + sizeof(int)) {throw std::runtime_error("Invalid encrypted data");}// 提取鹽值std::vector<unsigned char> salt(SALT_LENGTH);memcpy(salt.data(), encryptedData.c_str(), SALT_LENGTH);// 提取IV向量unsigned char iv[IV_LENGTH];memcpy(iv, encryptedData.c_str() + SALT_LENGTH, IV_LENGTH);// 提取密文長度int ciphertext_len;memcpy(&ciphertext_len, encryptedData.c_str() + SALT_LENGTH + IV_LENGTH, sizeof(int));// 提取密文const unsigned char* ciphertext = reinterpret_cast<const unsigned char*>(encryptedData.c_str() + SALT_LENGTH + IV_LENGTH + sizeof(int));// 生成密鑰std::vector<unsigned char> key = generateKey(password, salt.data());// 準備解密上下文EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();if (!ctx) {throw std::runtime_error("Failed to create cipher context");}// 初始化解密操作if (EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, key.data(), iv) != 1) {EVP_CIPHER_CTX_free(ctx);throw std::runtime_error("Failed to initialize decryption");}// 計算明文長度int plaintext_len = ciphertext_len;std::vector<unsigned char> plaintext(plaintext_len);// 執行解密int len;if (EVP_DecryptUpdate(ctx, plaintext.data(), &len, ciphertext, ciphertext_len) != 1) {EVP_CIPHER_CTX_free(ctx);throw std::runtime_error("Decryption failed");}plaintext_len = len;// 完成解密if (EVP_DecryptFinal_ex(ctx, plaintext.data() + len, &len) != 1) {EVP_CIPHER_CTX_free(ctx);throw std::runtime_error("Final decryption step failed - incorrect password?");}plaintext_len += len;// 釋放上下文EVP_CIPHER_CTX_free(ctx);// 返回明文return std::string(reinterpret_cast<char*>(plaintext.data()), plaintext_len);} catch (const std::exception& e) {std::cerr << "Decryption error: " << e.what() << std::endl;return "";}
}bool MarkdownEncryptor::saveToFile(const std::string& encryptedData, const std::string& filename) {std::ofstream file(filename, std::ios::binary);if (!file) {return false;}file.write(encryptedData.data(), encryptedData.size());return true;
}std::string MarkdownEncryptor::loadFromFile(const std::string& filename) {std::ifstream file(filename, std::ios::binary | std::ios::ate);if (!file) {return "";}std::streamsize size = file.tellg();file.seekg(0, std::ios::beg);std::string data(size, '\0');if (file.read(&data[0], size)) {return data;}return "";
}// main.cpp
int main() {// 創建加密器實例MarkdownEncryptor encryptor;// 添加用戶std::string username = "user1";std::string password = "securePassword123";if (encryptor.addUser(username, password)) {std::cout << "用戶 " << username << " 創建成功" << std::endl;} else {std::cout << "用戶 " << username << " 創建失敗" << std::endl;return 1;}// 驗證用戶if (encryptor.verifyUser(username, password)) {std::cout << "用戶驗證成功" << std::endl;} else {std::cout << "用戶驗證失敗" << std::endl;return 1;}// 創建一個markdown內容std::ostringstream markdown;markdown << "# 我的秘密文檔\n"<< "這是一個加密的文檔。\n"<< "## 章節1\n"<< "包含一些敏感信息...\n"<< "## 章節2\n"<< "更多的秘密內容...\n";// 加密內容std::string encrypted = encryptor.encrypt(markdown, password);if (encrypted.empty()) {std::cout << "加密失敗" << std::endl;return 1;}// 保存到文件if (encryptor.saveToFile(encrypted, "secret.md.enc")) {std::cout << "加密文件已保存" << std::endl;} else {std::cout << "保存文件失敗" << std::endl;return 1;}// 從文件加載std::string loaded = encryptor.loadFromFile("secret.md.enc");if (loaded.empty()) {std::cout << "加載文件失敗" << std::endl;return 1;}// 解密內容std::string decrypted = encryptor.decrypt(loaded, password);if (decrypted.empty()) {std::cout << "解密失敗 - 可能密碼錯誤" << std::endl;return 1;}// 顯示解密后的內容std::cout << "\n解密后的內容:\n" << decrypted << std::endl;return 0;
}
實現說明
這個解決方案提供了以下功能:
- 加密算法:使用AES-256-CBC對稱加密算法,提供高強度加密保護
- 密鑰派生:使用PBKDF2算法從密碼生成加密密鑰,增加暴力破解難度
- 用戶管理:支持添加用戶和密碼驗證功能
- 數據存儲:將加密數據保存到文件,包含所有必要的元數據(鹽值、IV向量等)
使用方法
- 創建
MarkdownEncryptor
實例 - 使用
addUser
添加用戶賬號和密碼 - 使用
verifyUser
驗證用戶身份 - 對
std::ostringstream
中的markdown內容使用encrypt
方法加密 - 使用
saveToFile
保存加密后的數據 - 解密時,先用
loadFromFile
加載數據,再用decrypt
方法解密
編譯注意事項
需要鏈接OpenSSL庫進行編譯,例如:
g++ main.cpp markdown_encryptor.cpp -o markdown_encrypt -lcrypto