]> pd.if.org Git - zpackage/blob - src/hash.c
remove stray debug fprintf
[zpackage] / src / hash.c
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <string.h>
4 #include <sys/types.h>
5 #include <sys/stat.h>
6 #include <fcntl.h>
7
8 #include "zpm.h"
9 #include "sha256.h"
10 #include "blake2.h"
11
12 static int hash_file(int fd, char *hash) {
13         unsigned char buf[4096];
14         ssize_t bytes;
15         unsigned char tmp[32];
16         int j;
17
18 #if 0
19         struct sha256_state md;
20         sha256_init(&md);
21         do {
22                 bytes = read(fd, buf, sizeof buf);
23                 if (bytes == -1) {
24                         return 0;
25                 }
26                 sha256_process(&md, buf, bytes);
27         } while (bytes);
28         sha256_done(&md, tmp);
29         for (j=0;j<32;j++) {
30                 sprintf(hash+j*2, "%02x", (unsigned)tmp[j]);
31         }
32         hash[64] = 0;
33
34 #else
35         struct blake2b_state__ blake;
36         blake2b_init(&blake, sizeof tmp);
37         do {
38                 bytes = read(fd, buf, sizeof buf);
39                 if (bytes == -1) {
40                         return 0;
41                 }
42                 blake2b_update(&blake, buf, bytes);
43         } while (bytes);
44         blake2b_final(&blake, tmp, sizeof tmp);
45         for (j=0;j<32;j++) {
46                 sprintf(hash+j*2, "%02x", (unsigned)tmp[j]);
47         }
48         hash[64] = 0;
49 #endif
50         return 1;
51 }
52
53 int main(int ac, char **av){
54         int rv;
55         char hash[65];
56         int input;
57         char *filename;
58         int i;
59
60         for (i=1; i < ac; i++) {
61                 filename = av[i];
62                 if (strcmp(filename, "-") == 0) {
63                         input = 0;
64                 } else {
65                         input = open(filename, O_RDONLY);
66                         if (input == -1) {
67                                 fprintf(stderr, "%s ", filename);
68                                 perror("zpm-hash1");
69                                 exit(EXIT_FAILURE);
70                         }
71                 }
72                 rv = hash_file(input, hash);
73                 close(input);
74                 if (rv == 0) {
75                         perror("zpm-hash2");
76                         exit(EXIT_FAILURE);
77                 }
78                 printf("%s\n", hash);
79         }
80
81         if (ac < 2) {
82                 filename = "-";
83                 rv = hash_file(0, hash);
84                 if (rv == 0) {
85                         perror("zpm-hash3");
86                         exit(EXIT_FAILURE);
87                 }
88                 printf("%s\n", hash);
89         }
90
91         return 0;
92 }