summaryrefslogtreecommitdiffstats
path: root/src/cryptsetup/cryptsetup-tokens/cryptsetup-token-util.c
blob: 4e3090bc9297b7e5ef85c98d1998a836412ecac1 (plain)
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
/* SPDX-License-Identifier: LGPL-2.1-or-later */

#include "cryptsetup-token-util.h"
#include "string-util.h"

int crypt_dump_buffer_to_hex_string(
                const char *buf,
                size_t buf_size,
                char **ret_dump_str) {

        int r;
        _cleanup_free_ char *dump_str = NULL;

        assert(buf || !buf_size);
        assert(ret_dump_str);

        for (size_t i = 0; i < buf_size; i++) {
                /* crypt_dump() breaks line after every
                 * 16th couple of chars in dumped hexstring */
                r = strextendf_with_separator(
                        &dump_str,
                        (i && !(i % 16)) ? CRYPT_DUMP_LINE_SEP : " ",
                        "%02hhx", buf[i]);
                if (r < 0)
                        return r;
        }

        *ret_dump_str = TAKE_PTR(dump_str);

        return 0;
}

int crypt_dump_hex_string(const char *hex_str, char **ret_dump_str) {

        int r;
        size_t len;
        _cleanup_free_ char *dump_str = NULL;

        assert(hex_str);
        assert(ret_dump_str);

        len = strlen(hex_str) >> 1;

        for (size_t i = 0; i < len; i++) {
                /* crypt_dump() breaks line after every
                 * 16th couple of chars in dumped hexstring */
                r = strextendf_with_separator(
                        &dump_str,
                        (i && !(i % 16)) ? CRYPT_DUMP_LINE_SEP : " ",
                        "%.2s", hex_str + (i<<1));
                if (r < 0)
                        return r;
        }

        *ret_dump_str = TAKE_PTR(dump_str);

        return 0;
}

int crypt_normalize_pin(const void *pin, size_t pin_size, char **ret_pin_string) {
        assert(pin || pin_size == 0);
        assert(ret_pin_string);

        if (pin_size == 0) {
                *ret_pin_string = NULL;
                return 0;
        }

        return make_cstring(pin, pin_size, MAKE_CSTRING_ALLOW_TRAILING_NUL, ret_pin_string);
}