-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustomhash.c
62 lines (51 loc) · 1.1 KB
/
customhash.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
#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[4096], *pos;
size_t bytes_read;
pos = buf;
bytes_read = fread(buf, 1, buf + sizeof(buf) - pos, f);
while (bytes_read && pos < (buf + sizeof(buf)))
{
pos += bytes_read;
bytes_read = fread(buf, 1, buf + sizeof(buf) - pos, f);
}
if (!feof(f))
{
errno = EIO;
return errno;
}
if (!EVP_Digest(buf, pos - buf, md, &md_size, EVP_sha1(), NULL))
{
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;
}