1 /*
2 * Copyright (c) 2012 Tim Ruehsen
3 * Copyright (c) 2015-2021 Free Software Foundation, Inc.
4 *
5 * This file is part of libwget.
6 *
7 * Libwget is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Lesser General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * Libwget is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with libwget. If not, see <https://www.gnu.org/licenses/>.
19 *
20 *
21 * Digest/hash helper routines
22 *
23 * 21.12.2012 Tim Ruehsen created
24 *
25 */
26
27 #include <config.h>
28
29 #include <stddef.h>
30
31 #include <wget.h>
32 #include "private.h"
33
34 /**
35 * \file
36 * \brief Hash convenience functions
37 * \defgroup libwget-hash Hash convenience functions
38 * @{
39 *
40 * Provides Hash helper functions
41 */
42
43 /**
44 * \param[in] algorithm The hash algorithm to use
45 * \param[out] out Output string buffer
46 * \param[in] outsize Size of output string buffer
47 * \param[in] fmt Printf-like format specifier
48 * \param[in] ... List of arguments
49 *
50 * Calculate the hash from the string generated via the
51 * printf-style \p fmt and the following arguments and place it as hexadecimal string
52 * into \p out.
53 *
54 * The ideal length of \p out would be wget_hash_get_len(type) * 2 + 1.
55 */
wget_hash_printf_hex(wget_digest_algorithm algorithm,char * out,size_t outsize,const char * fmt,...)56 void wget_hash_printf_hex(wget_digest_algorithm algorithm, char *out, size_t outsize, const char *fmt, ...)
57 {
58 char *plaintext = NULL;
59 va_list args;
60 size_t len;
61
62 va_start(args, fmt);
63 len = wget_vasprintf(&plaintext, fmt, args);
64 va_end(args);
65
66 if (plaintext) {
67 unsigned char digest[wget_hash_get_len(algorithm)];
68 int rc;
69
70 if ((rc = wget_hash_fast(algorithm, plaintext, len, digest)) == 0) {
71 wget_memtohex(digest, sizeof(digest), out, outsize);
72 } else {
73 *out = 0;
74 error_printf(_("Failed to hash (%d)\n"), rc);
75 }
76
77 xfree(plaintext);
78 }
79 }
80
81 /**@}*/
82