-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustomhashv3.c
85 lines (68 loc) · 1.45 KB
/
customhashv3.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
83
84
85
#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 = sizeof(md);
unsigned char buf[256];
int bytes_read;
BIO *filebio, *sha1bio;
filebio = BIO_new_fp(f, BIO_NOCLOSE);
if (!filebio)
{
errno = ENOMEM;
return errno;
}
sha1bio = BIO_new(BIO_f_md());
if (!sha1bio)
{
BIO_free(filebio);
errno = ENOMEM;
return errno;
}
BIO_set_md(sha1bio, EVP_sha1());
BIO_push(sha1bio, filebio);
bytes_read = BIO_read(sha1bio, buf, sizeof(buf));
while (bytes_read > 0)
{
bytes_read = BIO_read(sha1bio, buf, sizeof(buf));
}
if (bytes_read < 0)
{
BIO_free_all(sha1bio);
errno = EIO;
return errno;
}
if (BIO_gets(sha1bio, md, sizeof(md)) <= 0)
{
BIO_free_all(sha1bio);
errno = EFAULT;
return errno;
}
BIO_free_all(sha1bio);
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;
}