使用Crypto ++的AES示例

我一直在寻找互联网,以获得良好的 c + + AES代码示例/教程,教授encryption技术的基础知识和使用库,但到目前为止,我没有得到像样的材料运气。

好:易于理解(只是在旅途中学习的基础知识)。

Crypto ++ AES官方文档是一个很好的开始。 从我的档案中,AES的基本实现如下:

请参阅这里更多的解释,我build议你先理解algorithm ,然后尝试逐步了解每一行。

#include <iostream> #include <iomanip> #include "modes.h" #include "aes.h" #include "filters.h" int main(int argc, char* argv[]) { //Key and IV setup //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256- //bit). This key is secretly exchanged between two parties before communication //begins. DEFAULT_KEYLENGTH= 16 bytes byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ]; memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH ); memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE ); // // String and Sink setup // std::string plaintext = "Now is the time for all good men to come to the aide..."; std::string ciphertext; std::string decryptedtext; // // Dump Plain Text // std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl; std::cout << plaintext; std::cout << std::endl << std::endl; // // Create Cipher Text // CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH); CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv ); CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) ); stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() + 1 ); stfEncryptor.MessageEnd(); // // Dump Cipher Text // std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl; for( int i = 0; i < ciphertext.size(); i++ ) { std::cout << "0x" << std::hex << (0xFF & static_cast<byte>(ciphertext[i])) << " "; } std::cout << std::endl << std::endl; // // Decrypt // CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH); CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv ); CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) ); stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() ); stfDecryptor.MessageEnd(); // // Dump Decrypted Text // std::cout << "Decrypted Text: " << std::endl; std::cout << decryptedtext; std::cout << std::endl << std::endl; return 0; } 

有关安装细节:

  • 如何在Visual Studio 2010 Windows 7中安装Crypto ++?
  • * nix环境
  • 对于Ubuntu我做到了:

sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils