static void test_hashing(void) { static const struct test_data { const char * text; const char * result; int algo; } test_data[] = { { "moin", "06a998cdd13c50b7875775d4e7e9fa74", WGET_DIGTYPE_MD5 }, { "moin", "ba3cffcc93a92e08f82c33c55d887666fdf364ae", WGET_DIGTYPE_SHA1 }, { "moin", "2500d0ed4d0ea1b3ea9f7f57a5f16c2fba8ad15d05d3c057d42f9796f1250169", WGET_DIGTYPE_SHA256 }, { "moin", "e3ab1c142d6136fd938c810d13deaf47ccdb176687fab916611302ceb6a89787f45fdda2df544fec4f5a9a2a40916f316fcdf57bc27b5b757b7598da24c7c4c4", WGET_DIGTYPE_SHA512 }, }; unsigned char digest[64]; char digest_hex[sizeof(digest) * 2 + 1]; int rc; for (unsigned it = 0; it < countof(test_data); it++) { const struct test_data *t = &test_data[it]; if ((rc = wget_hash_fast(t->algo, t->text, strlen(t->text), digest)) == 0) { int len = wget_hash_get_len(t->algo); wget_memtohex(digest, len, digest_hex, len * 2 + 1); if (!strcmp(digest_hex, t->result)) ok++; else { failed++; info_printf("Failed [%u]: wget_hash_fast(%s,%d) -> %s (expected %s)\n", it, t->text, t->algo, digest_hex, t->result); } } else { failed++; info_printf("Failed [%u]: wget_hash_fast(%s,%d) failed with %d\n", it, t->text, t->algo, rc); } } }
/** * \param[out] digest_hex Output string buffer * \param[in] fmt Printf-like format specifier * \param[in] ... List of arguments * * Calculate the hexadecimal MD5 digest from the string generated via the * printf-style \p fmt and the following arguments. * * \p digest_hex must at least have a size of 33 bytes and will be zero terminated. * 33 calculates from wget_hash_get_len(WGET_DIGTYPE_MD5) * 2 + 1. */ void wget_md5_printf_hex(char *digest_hex, const char *fmt, ...) { char *plaintext; va_list args; size_t len; int rc; va_start(args, fmt); len = wget_vasprintf(&plaintext, fmt, args); va_end(args); if (plaintext) { unsigned char digest[wget_hash_get_len(WGET_DIGTYPE_MD5)]; if ((rc = wget_hash_fast(WGET_DIGTYPE_MD5, plaintext, len, digest)) == 0) { wget_memtohex(digest, sizeof(digest), digest_hex, sizeof(digest) * 2 + 1); } else { *digest_hex = 0; error_printf(_("Failed to MD5 hash (%d)\n"), rc); } xfree(plaintext); } }
static void test_utils(void) { int it; unsigned char src[1]; char dst1[3], dst2[3]; for (int ndst = 1; ndst <= 3; ndst++) { for (it = 0; it <= 255; it++) { src[0] = (unsigned char) it; wget_memtohex(src, 1, dst1, ndst); snprintf(dst2, ndst, "%02x", src[0]); if (strcmp(dst1, dst2)) { info_printf("buffer_to_hex failed: '%s' instead of '%s' (ndst=%d)\n", dst1, dst2, ndst); failed++; break; } } if (it >= 256) ok++; else failed++; } }