如何访问数以百万计的位进行哈希

How to access millions of bits for hashing

本文关键字:哈希 数以百万计 何访问 访问      更新时间:2023-10-16

我正在对可执行文件进行MD5哈希。我已经使用python脚本从可执行文件读取二进制文件到文本文件,但是如果我要将这个构造文件读取到C程序中,我将处理mb的数据,因为1和0被视为char s,每个1位数字取8位。是否有可能将它们分别读取为单个比特?如果我制作了一个10MB的数组来保存二进制转换长度和哈希填充所需的所有字符,那么程序的性能会有多差?如果这是不可想象的,有没有更好的方法来操纵数据?

既然你标注了C和c++,我选C。

有可能将这些读取为单个比特吗?

是的,每次从文件中读取8个字节,并将这些1 s和0 s连接成一个新字节。您不需要为此创建一个10MB的数组。

首先,从文件中读取8个字节。读取的char值将被转换为整数值(01),然后进行位移以生成一个新字节。

unsigned char bits[8];
while (fread(bits, 1, 8, file) == 8) {
    for (unsigned int i = 0; i < 8; i++) {
        bits[i] -= '0';
    }
    char byte = (bits[0] << 7) | (bits[1] << 6) |
                (bits[2] << 5) | (bits[3] << 4) |
                (bits[4] << 3) | (bits[5] << 2) |
                (bits[6] << 1) | (bits[7]     );
    /* update MD5 Hash here */
}

然后,用新读取的字节更新MD5哈希值。


Edit:由于典型的MD5实现必须在处理之前将输入分解为512位的块,因此您可以在实现本身中消除该开销(尽管不推荐),只需从文件中读取512位(64字节),然后直接更新哈希。

unsigned char buffer[64];
unsigned char bits[8];
unsigned int index = 0;
while (fread(bits, 1, 8, file) == 8) {
    for (unsigned int i = 0; i < 8; i++) {
        bits[i] -= '0';
    }
    buffer[index++] = (bits[0] << 7) | (bits[1] << 6) |
                      (bits[2] << 5) | (bits[3] << 4) |
                      (bits[4] << 3) | (bits[5] << 2) |
                      (bits[6] << 1) | (bits[7]     );
    if (index == 64) {
        index = 0;
        /* update MD5 hash with 64 byte buffer */
    }
}
/* This sends the remaining data to the MD5 hash function */
/* It's not likely that your file has exactly 512N chars */
if (index != 0) {
    while (index != 64) {
        buffer[index++] = 0;
    }
    /* update MD5 hash with the padded buffer. */
}