]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/gcrypt-util.c
tree-wide: remove Lennart's copyright lines
[thirdparty/systemd.git] / src / basic / gcrypt-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #if HAVE_GCRYPT
4 #include <gcrypt.h>
5
6 #include "gcrypt-util.h"
7 #include "hexdecoct.h"
8
9 void initialize_libgcrypt(bool secmem) {
10 const char *p;
11 if (gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P))
12 return;
13
14 p = gcry_check_version("1.4.5");
15 assert(p);
16
17 /* Turn off "secmem". Clients which wish to make use of this
18 * feature should initialize the library manually */
19 if (!secmem)
20 gcry_control(GCRYCTL_DISABLE_SECMEM);
21 gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
22 }
23
24 int string_hashsum(const char *s, size_t len, int md_algorithm, char **out) {
25 _cleanup_(gcry_md_closep) gcry_md_hd_t md = NULL;
26 size_t hash_size;
27 void *hash;
28 char *enc;
29
30 initialize_libgcrypt(false);
31
32 hash_size = gcry_md_get_algo_dlen(md_algorithm);
33 assert(hash_size > 0);
34
35 gcry_md_open(&md, md_algorithm, 0);
36 if (!md)
37 return -EIO;
38
39 gcry_md_write(md, s, len);
40
41 hash = gcry_md_read(md, 0);
42 if (!hash)
43 return -EIO;
44
45 enc = hexmem(hash, hash_size);
46 if (!enc)
47 return -ENOMEM;
48
49 *out = enc;
50 return 0;
51 }
52 #endif