[英]HMAC SHA256 calculation on large file (using system call)
I have the below code to generate a SHA256 HMAC hash:我有以下代码来生成 SHA256 HMAC hash:
HMAC(EVP_sha256(), key, key_len, (const unsigned char *)data, strlen(data), digest, &digest_len);
I would however like to generate HMAC SHA256 hash of a file.但是,我想生成文件的 HMAC SHA256 hash。 Please note the file is a big file (~80 MB) I will need to do this using system calls rather than directly using a shell command.
请注意该文件是一个大文件(~80 MB),我需要使用系统调用而不是直接使用 shell 命令来执行此操作。
Regards问候
If you have a large file then you can use HMAC_Update()
and HMAC_Final()
.如果你有一个大文件,那么你可以使用
HMAC_Update()
和HMAC_Final()
。 Here is a quick and dirty example:这是一个快速而肮脏的例子:
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <ssl/hmac.h>
int main(int argc, char *argv[])
{
FILE *f;
uint8_t buf[1024];
HMAC_CTX *ctx;
size_t ret;
uint8_t key[8] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
uint8_t *md;
int md_len;
int i;
if (argc < 2) {
printf("Usage: %s [FILE]\n", argv[0]);
return 1;
}
f = fopen(argv[1], "r");
if (!f) {
printf("Could not open file\n");
return 1;
}
ctx = HMAC_CTX_new();
HMAC_Init_ex(ctx, key, 8, EVP_sha256(), NULL);
md = (uint8_t *) malloc(HMAC_size(ctx));
while (!feof(f)) {
ret = fread(buf, 1, sizeof(buf), f);
HMAC_Update(ctx, &buf[0], ret);
}
HMAC_Final(ctx, md, &md_len);
for (i = 0; i < md_len; i ++)
printf("%02X", md[i]);
printf("\n");
HMAC_CTX_free(ctx);
fclose(f);
return 0;
}
The output: output:
$ ./hmac hmac
C477E7AA9EC9F0DD8C98F85B94A18BC954E0648BB0C7D302F5EDE3679A93A6E8
$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.