繁体   English   中英

将数据格式化为十六进制字符串以增加C语言中的MD5哈希计算

[英]Format Data as Hexadecimal String to Increase MD5 Hash Computation in C

我写了一段C代码,并在codereview.stackexchange上要求某人为我优化它。 但是,我不太了解他对优化的实现。

他的解决方案是:

  1. 编写一个自定义函数,将MD5哈希转换为十六进制字符串。
  2. 为整个字符串而不是每个单个字节调用printf ,因此减少了函数调用的次数。

除了一些小的更改外,大多数代码都保持不变。 但是,他在主函数之外编写了一个自定义函数,这实际上是优化的关键。 不幸的是,我并没有真正理解它。 有人可以在程序的其余部分中为我解释代码的第一部分吗?

在注释中说, // Format the data as a hexadecimal string. The buffer must have space for 2 * length + 1 characters. // Format the data as a hexadecimal string. The buffer must have space for 2 * length + 1 characters. 但是,为什么缓冲区必须有2倍的长度加1个字符的空格?

主要功能之外的第一部分代码:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <openssl/md5.h>

    // Format the data as a hexadecimal string. The buffer must have
    // space for `2 * length + 1` characters.
    const char *hexString(unsigned char *data, size_t length, char *buffer) {
        const char *hexDigits = "0123456789abcdef";
        char *dest = buffer;
        for (size_t i = 0; i < length; i++) {
            *dest++ = hexDigits[data[i] >> 4];
            *dest++ = hexDigits[data[i] & 0x0F];
        }
        *dest = 0;
        return buffer;
    }

其余代码:

int main(void) {
                FILE *infile = fopen("infile", "r");
                if (infile == NULL) {
                    perror("Cannot open input file");
                    exit(EXIT_FAILURE);
                }
                FILE *outfile = fopen("cout3","w");
                if (outfile == NULL) {
                    perror("Cannot open output file");
                    exit(EXIT_FAILURE);
                }

                // Read file line-by-line
                char *line = NULL;
                size_t linecap = 0;
                ssize_t lineLength;
                while ((lineLength = getline(&line, &linecap, infile)) != -1) {
                    if (lineLength > 0 && line[lineLength - 1] == '\n') {
                        // Remove newline character
                        lineLength -= 1;
                        line[lineLength] = 0;
                    }

                    // Compute MD5 hash
                    unsigned char md5hash[MD5_DIGEST_LENGTH];
                    MD5((unsigned char*)line, lineLength, md5hash);

                    // Print hash as hex string
                    char hexBuffer[2 * MD5_DIGEST_LENGTH + 1];
                    fputs(hexString(md5hash, MD5_DIGEST_LENGTH, hexBuffer), outfile);
                    fputc('\n', outfile);
                }
                free(line);

                // Close output files
                fclose(infile);
                fclose(outfile);
            }

任何帮助将不胜感激。

简而言之,您提到的自定义函数是将一个字节拆分为两个字节,这是该字节的可打印十六进制视图,因此缓冲区需要为2 *长度,因为输出是字符串,并且需要一个额外的字节字符“ \\ 0”的缓冲区末尾。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM