以下代码演示了如何使用Crypto++(AES/CBC模式)加密、解密二进制数据:
// // Created by gj on 12/23/19. // #include <iostream> #include <crypto++/aes.h> #include <crypto++/modes.h> #include <crypto++/sha.h> #include <crypto++/filters.h> #include <crypto++/files.h> namespace CryptoPP { using byte = unsigned char; } using namespace std; using namespace CryptoPP; int main(int argc, char *argv[]) { byte key[AES::DEFAULT_KEYLENGTH] = { '0', '1', '2', '3', '4', '5', '6', '7', '0', '1', '2', '3', '4', '5', '6', '7', }; byte iv[AES::BLOCKSIZE] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF }; std::string password = "testPassWord"; // encrypt // --------------------------------- int chunkSize = 20 * CryptoPP::AES::BLOCKSIZE; CryptoPP::CBC_Mode<CryptoPP::AES>::Encryption encryptor; encryptor.SetKeyWithIV(key, sizeof(key), iv); std::ofstream testOut("./test.enc", std::ios::binary); CryptoPP::FileSink outSink(testOut); CryptoPP::byte message[chunkSize]; CryptoPP::StreamTransformationFilter stfenc(encryptor, new CryptoPP::Redirector(outSink), BlockPaddingSchemeDef::NO_PADDING); for (int i = 0; i < chunkSize; i++) { message[i] = (CryptoPP::byte) i; std::cout << (int) (char) message[i] << ','; } cout << endl; stfenc.Put(message, chunkSize); stfenc.MessageEnd(); testOut.close(); // decrypt // ------------------------------------ // Because of some unknown reason increase chuksize by 1 block // chunkSize+=16; CryptoPP::byte cipher[chunkSize], decrypted[chunkSize]; CryptoPP::CBC_Mode<CryptoPP::AES>::Decryption decryptor; decryptor.SetKeyWithIV(key, sizeof(key), iv); std::ifstream inFile("./test.enc", std::ios::binary); inFile.read((char *) cipher, chunkSize); for (int i = 0; i < chunkSize; i++) { char c = cipher[i]; std::cout << (int) c << ','; } cout << endl; CryptoPP::ArraySink decSink(decrypted, chunkSize); CryptoPP::StreamTransformationFilter stfdec(decryptor, new CryptoPP::Redirector(decSink), BlockPaddingSchemeDef::NO_PADDING); stfdec.Put(cipher, chunkSize); stfdec.MessageEnd(); inFile.close(); for (int i = 0; i < chunkSize; i++) { std::cout << (int) (char) decrypted[i] << ','; } std::cout << std::endl; return 0; }