Cpp

CryptoPP:AES暗号化と復号化



Cryptopp Aes Encryption



CryptoPP:暗号化および復号化するaes

CryptoPPは強力なパスワードライブラリであり、公式Webサイトはhttps://www.cryptopp.com/です。上記にはより詳細な例と説明がありますが、サンプルプログラムはやや一方的なものであり、すべてのアプリケーションシナリオに対応できるわけではなく、2日間の調査の暗号化および復号化アルゴリズムの一部がパッケージ化されて共有されています。



AES

シンプルで失礼なダイレクトペーストコード



// AES encoding, returning base64 encoded data std::string crypto::aes_encrypt(unsigned char* key, int keylen, unsigned char* iv, std::string data) { std::string encrypt_str try { // Initialize the encoder The mode selected here is CBC_Mode CryptoPP::CBC_Mode::Encryption cbc_encription(key, keylen, iv) / / Set a stream format CryptoPP is a very useful module CryptoPP::StreamTransformationFilter stf_encription(cbc_encription, // Here the encrypted output stream is encoded in base64, if not needed, directly pass new CryptoPP::StringSink(encrypt_str) new CryptoPP::Base64Encoder(new CryptoPP::StringSink(encrypt_str)), // Fill mode is padding 0 CryptoPP::BlockPaddingSchemeDef::ZEROS_PADDING) // put will pass the data that needs to be encoded stf_encription.Put(reinterpret_cast(data.c_str()), data.length() + 1) stf_encription.MessageEnd() } catch (std::exception e) { std::cout << e.what() << std::endl } return encrypt_str }

他の個別のライブラリと比較して、Base64EncoderとHexEncoderに加えて、ストリームフォーマットツールがあります

// aes decrypt, the base64_data passed in here is the data obtained by base64 encoding after AES encryption. std::string crypto::aes_decrypt(unsigned char* key, int keylen, unsigned char* iv, std::string base64_data) { try { / / Limited ability, did not find the pre-processing interface of the input stream, here first do base64 decoding std::string aes_encrypt_data CryptoPP::Base64Decoder decoder decoder.Attach(new CryptoPP::StringSink(aes_encrypt_data)) decoder.Put(reinterpret_cast(base64_data.c_str()), base64_data.length()) decoder.MessageEnd() // There is nothing to say below, similar to AES encryption, get raw data std::string decrypt_data CryptoPP::CBC_Mode::Decryption cbc_description(key, keylen, iv) CryptoPP::StreamTransformationFilter stf_description(cbc_description, new CryptoPP::StringSink(decrypt_data), CryptoPP::BlockPaddingSchemeDef::ZEROS_PADDING) stf_description.Put(reinterpret_cast(aes_encrypt_data.c_str()) , aes_encrypt_data.length()) stf_description.MessageEnd() return decrypt_data } catch (std::exception e) { std::cout << e.what() << std::endl return '' } }