簡體   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