首页 > 解决方案 > 如何读取密文的所有十六进制值?

问题描述

有一个没有任何扩展名的密文,大小为 32 字节。因此,我可以用十六进制编辑器得到它的十六进制值,它的十六进制值是;

a3 0b 35 8f 14 4e fe 5e 27 5a bd 8c 53 8b a0 cb ae da d3 fc 87 8b 51 0b d6 37 3e 91 86 9f f3 c9

我试图用我的代码从密文中读取这些值,

ifstream stream;
unsigned char c;
char arr[2];
char cipherhex[65];
int i=0;
stream.open("ciphertext2");
while (!stream.eof()) {
    stream >> c;
    sprintf(arr, "%02x", c);
    cout << arr[0] << arr[1] << " ";
    cipherhex[i] = arr[0];
    cipherhex[i+1] = arr[1];
    i += 2;
}

但是,当我运行这段代码时,虽然有0x类十六进制值的条件,但它可以读取这些十六进制值;

a3 35 8f 14 4e fe 5e 27 5a bd 8c 53 8b a0 cb ae da d3 fc 87 8b 51 d6 37 3e 91 86 9f f3 c9 c9

该代码不能读取0b090c,但对于不同的密文它可以读取030e。我无法理解它如何读取030e但不能读取090b。提前致谢。

一般来说,读取十六进制值没有问题,但是读取我上面提到的特定值有问题。

标签: c++encryptionhexifstream

解决方案


您的代码中有几个错误:

  • 不以二进制模式打开文件。

  • 用于operator>>读取格式化字符,忽略空白字符。

  • 没有为 分配足够的内存arr[],导致 中的缓冲区溢出sprintf()

  • 用作您的!eof()循环条件

  • cipherhex读取完成后不以空值终止(可选)

试试这个:

ifstream stream;
char c, arr[3], cipherhex[65];
int cypherhexlen = 0;
stream.open("ciphertext2");
while ((cypherhexlen < 64) && stream.get(c)) {
    sprintf(arr, "%02x", static_cast<unsigned char>(c));
    cout << arr[0] << arr[1] << " ";
    cipherhex[cypherhexlen] = arr[0];
    cipherhex[cypherhexlen+1] = arr[1];
    cypherhexlen += 2;
}
cipherhex[cypherhexlen] = '\0';
// use cipherhex as needed...

或者,我会选择更像这样的东西:

ifstream stream;
unsigned char cipher[32];
stream.open("ciphertext2");
stream.read(reinterpret_cast<char*>(cipher), 32);
int cypherlen = stream.gcount();
for(int i = 0; i < cypherlen; ++i) {
    cout << hex << noshowbase << setw(2) << cipher[i] << " ";
}
// use cipher as needed...

推荐阅读