]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/gcrypt-util.c
util: introduce memcmp_safe()
[thirdparty/systemd.git] / src / basic / gcrypt-util.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
91e023d8 2
349cc4a5 3#if HAVE_GCRYPT
91e023d8
ZJS
4#include <gcrypt.h>
5
91e023d8 6#include "gcrypt-util.h"
b68f10bf 7#include "hexdecoct.h"
91e023d8
ZJS
8
9void 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
96d49011 17 /* Turn off "secmem". Clients which wish to make use of this
91e023d8
ZJS
18 * feature should initialize the library manually */
19 if (!secmem)
20 gcry_control(GCRYCTL_DISABLE_SECMEM);
21 gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
22}
4ac2ca1b
ZJS
23
24int string_hashsum(const char *s, size_t len, int md_algorithm, char **out) {
bd944e6e 25 _cleanup_(gcry_md_closep) gcry_md_hd_t md = NULL;
4ac2ca1b
ZJS
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}
b68f10bf 52#endif