]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/gcrypt-util.c
Merge pull request #2702 from poettering/resolved-iterate-fix
[thirdparty/systemd.git] / src / shared / gcrypt-util.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4 This file is part of systemd.
5
6 Copyright 2012 Lennart Poettering
7
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
12
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
17
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <gcrypt.h>
23
24 #include "hexdecoct.h"
25 #include "gcrypt-util.h"
26
27 void initialize_libgcrypt(bool secmem) {
28 const char *p;
29 if (gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P))
30 return;
31
32 p = gcry_check_version("1.4.5");
33 assert(p);
34
35 /* Turn off "secmem". Clients which wish to make use of this
36 * feature should initialize the library manually */
37 if (!secmem)
38 gcry_control(GCRYCTL_DISABLE_SECMEM);
39 gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
40 }
41
42 int string_hashsum(const char *s, size_t len, int md_algorithm, char **out) {
43 gcry_md_hd_t md = NULL;
44 size_t hash_size;
45 void *hash;
46 char *enc;
47
48 initialize_libgcrypt(false);
49
50 hash_size = gcry_md_get_algo_dlen(md_algorithm);
51 assert(hash_size > 0);
52
53 gcry_md_open(&md, md_algorithm, 0);
54 if (!md)
55 return -EIO;
56
57 gcry_md_write(md, s, len);
58
59 hash = gcry_md_read(md, 0);
60 if (!hash)
61 return -EIO;
62
63 enc = hexmem(hash, hash_size);
64 if (!enc)
65 return -ENOMEM;
66
67 *out = enc;
68 return 0;
69 }