【发布时间】:2017-03-25 05:30:10
【问题描述】:
我正在使用库 Crypto++ 来加密/解密数据。官方页面是https://www.cryptopp.com。我正在关注this tutorial。它展示了如何在Crypto++ 中使用分组密码。您可以使用 find 关键字“使用分组密码”查看此部分。
我可以顺利运行演示。他们使用密钥加密数据,然后使用相同的密钥解密数据。我想将代码拆分为 encrypt() 和 decrypt() 函数。
你可以在下面看到我的encrypt() 函数。
包含部分:
#include "E:\Working\Improve\CPP\cryptopp565\osrng.h"
using CryptoPP::AutoSeededRandomPool;
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <string>
using std::string;
#include <cstdlib>
using std::exit;
#include "E:\Working\Improve\CPP\cryptopp565\cryptlib.h"
using CryptoPP::Exception;
#include "E:\Working\Improve\CPP\cryptopp565\hex.h"
using CryptoPP::HexEncoder;
using CryptoPP::HexDecoder;
#include "E:\Working\Improve\CPP\cryptopp565\filters.h"
using CryptoPP::StringSink;
using CryptoPP::StringSource;
using CryptoPP::StreamTransformationFilter;
#include "E:\Working\Improve\CPP\cryptopp565\aes.h"
using CryptoPP::AES;
#include "E:\Working\Improve\CPP\cryptopp565\ccm.h"
#include "E:\Working\Improve\CPP\cryptopp565\modes.h"
using CryptoPP::ECB_Mode;
#include <fstream>
#include "assert.h"
代码正文:
// My encrypt function
void encrypt(byte cbCipherText[AES::BLOCKSIZE], byte *plainText,
byte key[AES::DEFAULT_KEYLENGTH], int sizeKey) {
int size = sizeof(key);
ECB_Mode<AES>::Encryption Encryptor(key, sizeKey);
Encryptor.ProcessData(cbCipherText, plainText, sizeof(plainText));
}
void main() {
byte PlainText[] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o',
'r', 'l', 'd', 0x0, 0x0, 0x0, 0x0, 0x0};
byte key[AES::DEFAULT_KEYLENGTH];
::memset(key, 0x01, AES::DEFAULT_KEYLENGTH);
// Encrypt data
int size = sizeof(key);
int default = AES::DEFAULT_KEYLENGTH;
ECB_Mode<AES>::Encryption Encryptor(key, size);
// Next three lines are tutorial's code for encrypt
byte cbCipherText[AES::BLOCKSIZE];
Encryptor.ProcessData(cbCipherText, PlainText, sizeof(PlainText));
ECB_Mode<AES>::Decryption Decryptor(key, sizeof(key));
// Next two lines are my code to call the encrypt() function, I "cloned" the
// code
// from above three line!. Comment out them we will have the code like the
// demo.
byte myCipherText[AES::BLOCKSIZE];
encrypt(myCipherText, PlainText, key, size);
// Decrypt
byte cbRecoveredText[AES::BLOCKSIZE];
Decryptor.ProcessData(cbRecoveredText, cbCipherText, sizeof(cbCipherText));
// std::string PlainText ="Voltaire said, Prejudices are what fools use for
//reason";
cout << endl << "Recovered text: " << cbRecoveredText << endl;
getchar();
}
密钥是使用值\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1 创建的。在演示代码中,键的值永远不会改变,其大小始终为 16。
当我调用我的encrypt() 函数并将key 传递给它时,密钥大小(sizeof(key))在创建时为 16,但在传递给函数后,长度始终为 4(!)。键值为x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1\x1ĂŒĂŒĂŒĂŒĂŒĂŒĂŒĂŒHello World (!!!)。
因此,如果我跳入函数,我的代码总是会收到错误"AES: 4 is not valid key length"。
我不明白为什么会发生这种情况以及如何解决它。任何帮助将不胜感激!
【问题讨论】:
-
您声称收到“AES: 4 is not valid key length”错误。但是,您永远不会在
encrypt函数中的任何地方传递size(计算为sizeof(key))。那你是怎么解决这个错误的? -
请更改第一个#include。它阻止我继续阅读。
标签: c++ arrays pointers sizeof