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