File: hash_printf.c

package info (click to toggle)
wget2 2.2.0%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 22,468 kB
  • sloc: ansic: 121,166; sh: 11,559; makefile: 878; xml: 182; sed: 16
file content (95 lines) | stat: -rw-r--r-- 2,395 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
 * Copyright (c) 2012 Tim Ruehsen
 * Copyright (c) 2015-2024 Free Software Foundation, Inc.
 *
 * This file is part of libwget.
 *
 * Libwget is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Libwget is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with libwget.  If not, see <https://www.gnu.org/licenses/>.
 *
 *
 * Digest/hash helper routines
 *
 * 21.12.2012  Tim Ruehsen  created
 *
 */

#include <config.h>

#include <stddef.h>

#include <wget.h>
#include "private.h"

/**
 * \file
 * \brief Hash convenience functions
 * \defgroup libwget-hash Hash convenience functions
 * @{
 *
 * Provides Hash helper functions
 */

/**
 * \param[in] algorithm The hash algorithm to use
 * \param[out] out Output string buffer
 * \param[in] outsize Size of output string buffer
 * \param[in] fmt Printf-like format specifier
 * \param[in] ... List of arguments
 *
 * Calculate the hash from the string generated via the
 * printf-style \p fmt and the following arguments and place it as hexadecimal string
 * into \p out.
 *
 * The ideal length of \p out would be wget_hash_get_len(type) * 2 + 1.
 */
void wget_hash_printf_hex(wget_digest_algorithm algorithm, char *out, size_t outsize, const char *fmt, ...)
{
	char *plaintext = NULL;
	va_list args;
	size_t len;

	va_start(args, fmt);
	len = wget_vasprintf(&plaintext, fmt, args);
	va_end(args);

	if (!plaintext)
		return;

	unsigned char tmp[256], *digest = tmp;
	size_t digestlen = wget_hash_get_len(algorithm);

	if (digestlen > sizeof(tmp)) {
		digest = wget_malloc(digestlen);
	}

	if (digest) {
		int rc;

		if ((rc = wget_hash_fast(algorithm, plaintext, len, digest)) == 0) {
			wget_memtohex(digest, digestlen, out, outsize);
		} else {
			*out = 0;
			error_printf(_("Failed to hash (%d)\n"), rc);
		}

		if (digest != tmp)
			xfree(digest);
	} else {
		error_printf(_("%s: Failed to malloc %zu bytes\n"), __func__, digestlen);
	}

	xfree(plaintext);
}

/**@}*/