-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustomhashv2.c
82 lines (69 loc) · 1.44 KB
/
customhashv2.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <stdio.h>
#include <errno.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
static int hash(FILE *f)
{
int err, i;
unsigned char md[SHA_DIGEST_LENGTH];
unsigned int md_size;
unsigned char buf[256];
size_t bytes_read;
EVP_MD_CTX *ctx = EVP_MD_CTX_new();
if (!ctx)
{
errno = ENOMEM;
return errno;
}
if (!EVP_DigestInit(ctx, EVP_sha1()))
{
EVP_MD_CTX_free(ctx);
errno = EFAULT;
return errno;
}
bytes_read = fread(buf, 1, sizeof(buf), f);
while (bytes_read)
{
if (!EVP_DigestUpdate(ctx, buf, bytes_read))
{
EVP_MD_CTX_free(ctx);
errno = EFAULT;
return errno;
}
bytes_read = fread(buf, 1, sizeof(buf), f);
}
if (!feof(f))
{
EVP_MD_CTX_free(ctx);
errno = EIO;
return errno;
}
if (!EVP_DigestFinal(ctx, md, &md_size))
{
EVP_MD_CTX_free(ctx);
errno = EFAULT;
return errno;
}
for (i = 0; i < md_size; i++)
printf("%02x", md[i]);
puts("");
return 0;
}
int main(int argc, char **argv)
{
int err;
FILE *f = stdin;
if (argc > 1) {
f = fopen(argv[1], "rb");
if (!f) {
perror(NULL);
return errno;
}
}
err = hash(f);
if (err)
perror(NULL);
if (argc > 1)
fclose(f);
return err;
}