gpt4 book ai didi

c++ - 如何从文件中读取前 256 位并将它们存储在两个数组中

转载 作者:行者123 更新时间:2023-11-30 17:51:40 25 4
gpt4 key购买 nike

我正在编码一个密码,其 key 文件长为 256 位。其中 128 位必须输入 key ,128 位必须输入 IV。我明确定义了这些数组的大小,然后读取,但我得到的输出仍然是 Key 具有大约 148 位设置,而 IV 的设置较小。最后它给出了堆栈粉碎错误。

int main(int argc,char *argv[]) {

if(argc < 4 || !argv[1] || !argv[2]) {
cout << "Usage: Encoding: " << argv[0] << " [plaintext-file] [key-file] [cipher-file]" << endl;
cout << "Usage: Decoding: " << argv[0] << " [cipher-file] [key-file] [plaintext-file]" << endl;
return 0;
}

unsigned char key[16], iv[16];
unsigned long i;

// read input file and size etc
FILE* in_file = fopen(argv[1],"rb");
if(!in_file) {
cout << "Error opening read file" << endl;
return 0;
}

fseek(in_file,0,SEEK_END);
unsigned int msglength = ftell(in_file);
cout << "Msglength:" << msglength << endl;

unsigned char * mem_ptr = (unsigned char*)malloc(msglength);
if(!mem_ptr) {
cout << "Error allocating memory" << endl;
fclose(in_file);
return 0;
}

rewind(in_file);
fread(mem_ptr,1,msglength,in_file);
fclose(in_file);

// read keyfile etc
FILE* key_file = fopen(argv[2],"rb");
if(!key_file) {
cout << "Error opening key file" << endl;
return 0;
}

fseek(key_file,0,SEEK_END);
unsigned int key_size = ftell(key_file);
cout << "Key Size:" << key_size << endl;
unsigned char * key_ptr = (unsigned char*)malloc(key_size);
if(!key_ptr) {
cout << "Error allocating memory" << endl;
fclose(key_file);
return 0;
}

rewind(key_file);
fread(key_ptr,1,key_size,key_file);

cout << "sizeof key"<<sizeof(key)<<" sizeof iv" << sizeof(iv) << endl;
for (i=0; i<256; i++) {
if (i<128) key[i] = key_ptr[i];
else iv[i-128] = key_ptr[i];
}
cout << key_ptr << endl;
cout << "Key:" << key << endl << "IV:" << iv << endl;
}

输出

Msglength:15
Key Size:257
sizeof key16 sizeof iv16
abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678

Key:abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678
IV:abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678

*** stack smashing detected ***: ./a.out terminated
Segmentation fault (core dumped)

知道我哪里出错了吗?

最佳答案

您的keyiv的大小都是16。

unsigned char key[16], iv[16];

所以这不好。

for (i=0; i<256; i++) {
if (i<128) key[i] = key_ptr[i];
else iv[i-128] = key_ptr[i];
}

你写错了,写到了这两个数组的末尾。

关于c++ - 如何从文件中读取前 256 位并将它们存储在两个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16590755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com