二进制文件的C获取哈希 [英] Getting hash of a binary file C

查看:140
本文介绍了二进制文件的C获取哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得一个二进制文件的名字我的哈希值。我曾尝试以下,但随后意识到 SHA1()是字符串(文件名)返回的哈希值。但我想对文件本身运行它。如何做到这一点的任何指针将是巨大的。

 的char *文件名=/斌/ LS
unsigned char型散[SHA_DIGEST_LENGTH]
SHA1((无符号字符*)文件名,strlen的(文件名),散列);


解决方案

感谢大家的意见,我解决了这个问题。我在这里张贴code,那么其他人可能会发现它是有益的。

 无效getFileHash(CHAR *文件名){unsigned char型结果[2 * SHA_DIGEST_LENGTH]。
unsigned char型散[SHA_DIGEST_LENGTH]
INT I;
FILE * F = FOPEN(文件名,RB);
SHA_CTX mdContent;
诠释字节;
unsigned char型数据[1024];如果(F == NULL){
    的printf(%s不能打开文件\\ n,文件名);
    出口(1);
}SHA1_Init(安培; mdContent);
而((字节= FREAD(数据,1,1024,F))!= 0){    SHA1_Update(安培; mdContent,数据,字节);
}SHA1_Final(哈希,和放大器; mdContent);对于(i = 0; I< SHA_DIGEST_LENGTH;我++){
    的printf(%02X,哈希[我]);
}
的printf(\\ n);
/ **如果你想看到的哈希的纯文本* /
对于(i = 0; I< SHA_DIGEST_LENGTH;我++){
    的sprintf((字符*)及(结果[我* 2]),%02X,散列[I]);
}的printf(%S \\ n,结果);FCLOSE(F);
}

I want to get hash of a binary file whose name I have. I have tried the following, but then realized that SHA1() is returning hash value for the string ( name of the file). But I want to run it on the file itself. Any pointers on how to do that would be great.

char *fileName = "/bin/ls"
unsigned char hash[SHA_DIGEST_LENGTH];
SHA1((unsigned char *)fileName, strlen(fileName),hash);

解决方案

Thanks to everyone's comments I solved the problem. I am posting the code here, so others might find it beneficial.

void getFileHash(char *fileName){

unsigned char result[2*SHA_DIGEST_LENGTH];
unsigned char hash[SHA_DIGEST_LENGTH];
int i;
FILE *f = fopen(fileName,"rb");
SHA_CTX mdContent;
int bytes;
unsigned char data[1024];

if(f == NULL){
    printf("%s couldn't open file\n",fileName);
    exit(1);
}

SHA1_Init(&mdContent);
while((bytes = fread(data, 1, 1024, f)) != 0){

    SHA1_Update(&mdContent, data, bytes);
}

SHA1_Final(hash,&mdContent);

for(i=0;i<SHA_DIGEST_LENGTH;i++){
    printf("%02x",hash[i]);
}
printf("\n");
/** if you want to see the plain text of the hash */
for(i=0; i < SHA_DIGEST_LENGTH;i++){
    sprintf((char *)&(result[i*2]), "%02x",hash[i]);
}

printf("%s\n",result);

fclose(f);
}

这篇关于二进制文件的C获取哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆