es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

El hash SHA1 del objeto git calculado por mi programa no coincide con el de git.

Estoy escribiendo un programa en C que replicaría los hashes SHA1 que da git, pero el hash que da git cambia y nunca coincide con el de mi programa. No creo que haya nada mal con mi implementación de SHA1. He intentado substituir mi implementación por otra, pero todavía obtengo los mismos resultados. Este es mi código:

sha1.h:

“`c

#ifndef SHA1_H
#define SHA1_H

#include <stdint.h>

typedef struct {
uint32_t state[5];
uint32_t count[2];
unsigned char buffer[64];
} SHA1_CTX;

void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]);

void SHA1Init(SHA1_CTX *context);

void SHA1Update(SHA1_CTX *context</stdint.h>

Tags:  ,

Answer

  1. Avatar for davy.ai

    El problema con el código está en la función object_hash. No está contando adecuadamente los caracteres de salto de línea (\n) al calcular el tamaño del objeto. Esto hace que el tamaño del objeto sea diferente al tamaño utilizado por Git, lo que resulta en un hash diferente.

    Para solucionar esto, la función object_hash debería agregar 1 al tamaño por cada carácter de salto de línea en object->data. Esto se puede hacer usando un bucle para iterar sobre cada carácter de los datos y comprobando si es un carácter de salto de línea.

    Aquí hay una función object_hash actualizada que tiene en cuenta los caracteres de salto de línea:

    char *object_hash(struct object *object)
    {
        /* Obtener el tamaño del objeto */
        int size = object->size;
        /* Tamaño a cadena */
        char *sizeStr = malloc(20);
        sprintf(sizeStr, "%d", size);
        size += strlen(objectTypeStrings[object->type]);
        size += strlen(sizeStr);
        size += 2;
    
        // Contar caracteres de salto de línea
        int newlines = 0;
        for (int i = 0; i < object->size; i++) {
            if (object->data[i] == '\n') {
                newlines++;
            }
        }
    
        size += newlines;
    
        char *format = malloc(size + 1);
        sprintf(format, "%s %s\n%s", objectTypeStrings[object->type], sizeStr, object->data);
        /* Obtener el hash del objeto */
        char *hash = calloc(41, sizeof(char));
        SHA1(hash, format, size);
        free(format);
        free(sizeStr);
        return hash;
    }
    

Comments are closed.