代码之家  ›  专栏  ›  技术社区  ›  h5law

在C语言中使用OpenSSL的SHA1与Apple Silicon

  •  1
  • h5law  · 技术社区  · 1 年前

    我正在构建一个git克隆并使用hash文件命令。我目前正在尝试计算一个已知字符串的SHA1哈希,并有此代码和以下问题:

    #include <openssl/sha.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int hashFile(char *file_name, int ww) {
        int i, ret;
        size_t size_len;
        unsigned long file_size;
        char path[56];
        unsigned char hash[SHA_DIGEST_LENGTH];
        char *token, *type, *blob_content, *content;
    
        FILE *src = fopen(file_name, "r");
        if (ferror(src)) {
            perror("Unable to read file");
            return 1;
        }
        fseek(src, 0L, SEEK_END);
        file_size = ftell(src);
        rewind(src);
        size_len = snprintf(NULL, 0, "%lu", file_size);
    
        char *buffer = (char *)malloc((size_t)file_size + 1);
        fread(buffer, sizeof(char), file_size, src);
        buffer[file_size] = '\0';
    
        blob_content = (char *)malloc((7 + sizeof(unsigned long) + file_size + 1) *
                                      sizeof(char));
        snprintf(blob_content, 7 + size_len + 1, "blob %lu\\0", file_size);
        strcat(blob_content, buffer);
    
        SHA1((unsigned char *)blob_content, strlen(blob_content), hash);
        printf("%s\n", hash);
    
        free(blob_content);
        free(buffer);
    
        return 0;
    }
    
    void printHashHelp() {
        printf("usage: twat hash-file [options] <file_name>\n");
        printf("\n");
        printf("options:\n");
        printf("\t-w: write contents to objects store\n");
    }
    
    $ clang --std=c17 -fmodules -fprebuilt-module-path=. -I/opt/homebrew/opt/openssl/include cmd.c comp.c init.c cat.c hash.c -o twat -v
    ...
    Undefined symbols for architecture arm64:
      "_SHA1", referenced from:
          _hashFile in hash-fc3ff3.o
    ld: symbol(s) not found for architecture arm64
    

    我应该如何链接并启用SHA1在M2 Max上工作?什么 clang 如果这不正确,我应该使用命令吗?

    我一直在尝试不同的链接方法 openssl/sha.h 并被认为已经得到了它,但目前还没有得到工作的功能。

    下列的 How to use SHA1 hashing in C programming 我试图使用链接库,但遇到编译器链接失败。

    1 回复  |  直到 1 年前
        1
  •  1
  •   selbie    1 年前

    追加

    -L/opt/homebrew/lib -lcrypto
    

    到您的命令行。

    此外,你的malloc和snprintf看起来很奇怪。整个+1和+7看起来容易出错

    这样会更好:

    char header[100] = {0};  // 100 is big enough for the entire "blob 12345" thing regardless of how big the file is
    
    SHA1_CTX ctx = {0};
    SHA1_Init(&ctx);
    sprintf(header, "blob %lu", file_size);
    SHA1_Update(&ctx, header, strlen(header));
    SHA1_Update(&ctx, buffer, file_size);
    SHA1_Final(hash, &ctx);
    

    然后,如果你真的想变得迂腐,请确保在非Unix上以二进制文件的形式打开文件:

    #ifdef _WIN32
        char* flags = "rb";
    #else
        char* flags = "r";
    #endif
    
    FILE *src = fopen(file_name, flags);
    
    推荐文章