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