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