如何读取密文的所有十六进制值?

时间:2018-11-07 20:16:22

标签: c++ encryption hex ifstream

有一个密文,没有任何扩展名,长度为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

该代码无法读取 0b 09 0c ,但是对于不同的密文,它可以读取 03 0e 。我不明白它如何读取 03 0e ,但不能读取 09 0b 。预先感谢。

通常,读取十六进制值没有问题,但是读取我上面提到的特定值有问题。

1 个答案:

答案 0 :(得分:0)

您的代码中有几个错误:

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

  • 使用operator>>读取格式的字符,而忽略空白字符。

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

  • using !eof() as your loop condition

  • 读取完成后不能以空终止的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...
相关问题