Debian Codegraph @

src/basic/sha256.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <unistd.h>
4
5 #include "alloc-util.h"
6 #include "hexdecoct.h"
7 #include "sha256.h"
8 #include "string-util.h"
9
10 int sha256_fd(int fd, uint64_t max_size, uint8_t ret[static SHA256_DIGEST_SIZE]) {
11 struct sha256_ctx ctx;
12 uint64_t total_size = 0;
13
14 sha256_init_ctx(&ctx);
15
16 for (;;) {
17 uint8_t buffer[64 * 1024];
18 ssize_t n;
19
20 n = read(fd, buffer, sizeof(buffer));
21 if (n < 0)
22 return -errno;
23 if (n == 0)
24 break;
25
26 if (!INC_SAFE(&total_size, n) || total_size > max_size)
27 return -EFBIG;
28
29 sha256_process_bytes(buffer, n, &ctx);
30 }
31
32 sha256_finish_ctx(&ctx, ret);
33 return 0;
34 }
35
36 int parse_sha256(const char *s, uint8_t ret[static SHA256_DIGEST_SIZE]) {
37 _cleanup_free_ uint8_t *data = NULL;
38 size_t size = 0;
39 int r;
40
41 if (!sha256_is_valid(s))
42 return -EINVAL;
43
44 r = unhexmem_full(s, SHA256_DIGEST_SIZE * 2, false, (void**) &data, &size);
45 if (r < 0)
46 return r;
47 assert(size == SHA256_DIGEST_SIZE);
48
49 memcpy(ret, data, size);
50 return 0;
51 }
52
53 bool sha256_is_valid(const char *s) {
54 return s && in_charset(s, HEXDIGITS) && (strlen(s) == SHA256_DIGEST_SIZE * 2);
55 }