Cryptopp AES示例:修订间差异
跳到导航
跳到搜索
(创建页面,内容为“<syntaxhighlight lang="cpp"> #include <iostream> #include <string> #include "cryptlib.h" #include "aes.h" #include "modes.h" #include "files.h" #include "osrng.h" #include "hex.h" using namespace CryptoPP; using namespace std; int main(int argc, char* argv[]) { // 建立隨機亂數產生器 // AutoSeededRandomPool prng; // 將金鑰與 IV 放置於安全的記憶體空間 // SecByteBlock key(AES::DEFAULT_KEYLENGTH); // 採用預設的金鑰…”) |
无编辑摘要 |
||
第1行: | 第1行: | ||
< | <pre> | ||
#include <iostream> | #include <iostream> | ||
#include <string> | #include <string> | ||
第83行: | 第83行: | ||
return EXIT_SUCCESS; | return EXIT_SUCCESS; | ||
} | } | ||
</ | </pre> |
2025年1月31日 (五) 20:24的最新版本
#include <iostream> #include <string> #include "cryptlib.h" #include "aes.h" #include "modes.h" #include "files.h" #include "osrng.h" #include "hex.h" using namespace CryptoPP; using namespace std; int main(int argc, char* argv[]) { // 建立隨機亂數產生器 // AutoSeededRandomPool prng; // 將金鑰與 IV 放置於安全的記憶體空間 // SecByteBlock key(AES::DEFAULT_KEYLENGTH); // 採用預設的金鑰長度(128 位元) // SecByteBlock key(AES::MAX_KEYLENGTH); // 採用最長的金鑰長度(256 位元) // SecByteBlock key(24); // 自行指定金鑰長度(192 位元) // 產生隨機金鑰與 IV // prng.GenerateBlock(key, key.size()); byte key[AES::DEFAULT_KEYLENGTH] = "abcd1234"; // 原始資料 std::string plain = "Crypto++ is a free C++ library for cryptography"; // 用來儲存密文與明文的變數 std::string cipher, encoded, recovered; std::cout << "key:" << key << std::endl; std::cout << "原始資料:" << plain << std::endl; try { // 採用 AES-ECB 加密 ECB_Mode<AES>::Encryption e; // 設定金鑰 e.SetKey(key, sizeof(key)); // 進行加密 StringSource s(plain, true, new StreamTransformationFilter(e, new StringSink(cipher) ) // StreamTransformationFilter ); // StringSource } catch(const Exception& e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } // Pretty print cipher text StringSource ss2( cipher, true, new HexEncoder( new StringSink( encoded ) ) // HexEncoder ); // StringSource std::cout << "cipher text: " << encoded << std::endl; try { // 採用 AES-ECB 解密 ECB_Mode<AES>::Decryption d; // 設定金鑰與 IV d.SetKey(key, sizeof(key)); // 進行解密 StringSource s(cipher, true, new StreamTransformationFilter(d, new StringSink(recovered) ) // StreamTransformationFilter ); // StringSource } catch(const Exception& e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } std::cout << "解開的明文:" << recovered << std::endl; return EXIT_SUCCESS; }