【发布时间】:2017-07-19 09:29:57
【问题描述】:
我正在尝试将 AES 密钥写入文件,然后再读取。我正在使用 Crypto++ 库,并且 AES 密钥初始化如下。下面,byte 是 unsigned char 的 typedef。
byte key[CryptoPP::AES::MAX_KEYLENGTH]
密钥长度为 32 个字节。我尝试将其写入文件:
FILE* file = fopen("C:\\key", "wb");
fwrite(key, 1, sizeof(key), file);
fclose(file);
并使用以下方法恢复它:
FILE* read_file = fopen("C:\\key", "rb");
fseek(read_file, 0, SEEK_END);
long int size = ftell(read_file);
fclose(read_file);
read_file = fopen("C:\\key", "rb");
unsigned char * in = (unsigned char *)malloc(size);
byte readed_key = fread(in, sizeof(unsigned char), size, read_file);
fclose(read_file);
if (key == readed_key)
{
cout << "this is the right key !";
}
free(in);
但是,我收到一条错误消息:
不兼容的操作数类型:byte* 和 byte。
我不明白为什么,因为 readed_key 和 key 是用 byte 而不是 byte* 初始化的。
我在 Crypto++ wiki 上查看了AES,生成的密钥如下。我发现我只是在创建密钥(而不是生成它):
SecByteBlock key(0x00, AES::MAX_KEYLENGTH);
rnd.GenerateBlock( key, key.size() );
这样我就不能用了
std::vector<byte> key(32);
rnd.GenerateBlock(key, key.size());
因为rnd.Generateblock无法转换std::vector< byte > into byte*
这让我发疯了......
【问题讨论】:
-
你应该避免
FILE*;并坚持使用 C++ 并使用ifstream。或者,使用 Crypto++FileSource。另请参阅 Crypto++ wiki 上的 std::byte 和问题跟踪器中的 Issue 442, Test C++17 byte change with dry runs from various projects。byte正准备更改为CryptoPP::byte。 -
How to read a binary file into a vector of unsigned chars、Loading a file into a vector<char>、Efficient way of reading a file into an std::vector<char>?、Reading and writing a std::vector into a file correctly with iterators、Reading and writing a std::vector into a file correctly、How to read a file into vector in C++? 等可能重复
标签: c++ arrays vector file-io crypto++