logo

utils-std

Collection of commonly available Unix tools git clone https://anongit.hacktivis.me/git/utils-std.git/

t_sha512.c (2251B)


  1. // utils-std: Collection of commonly available Unix tools
  2. // SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
  3. // SPDX-License-Identifier: 0BSD
  4. #define _POSIX_C_SOURCE 200809L
  5. #include "../lib/sha512.h"
  6. #include "../lib/strconv.h"
  7. #include <assert.h>
  8. #include <stdio.h> // printf
  9. #include <string.h> // memcmp
  10. int counter = 0;
  11. int err = 0;
  12. static void
  13. t_sha512(const char *name,
  14. const void *data,
  15. size_t datalen,
  16. const char expected[SHA512_DIGEST_LENGTH * 2])
  17. {
  18. int id = ++counter;
  19. struct sha512 ctx;
  20. sha512_init(&ctx);
  21. sha512_update(&ctx, data, datalen);
  22. uint8_t res[SHA512_DIGEST_LENGTH] = "";
  23. sha512_sum(&ctx, res);
  24. char got[SHA512_DIGEST_LENGTH * 2] = "";
  25. bytes2hex(res, sizeof(res), got, sizeof(got));
  26. if(memcmp(expected, got, SHA512_DIGEST_LENGTH * 2) == 0)
  27. {
  28. printf("ok %d - %s\n", id, name);
  29. return;
  30. }
  31. err = 1;
  32. fputs("# Expected: ", stdout);
  33. fwrite(expected, SHA512_DIGEST_LENGTH * 2, 1, stdout);
  34. fputs("\n", stdout);
  35. fputs("# Got: ", stdout);
  36. fwrite(got, SHA512_DIGEST_LENGTH * 2, 1, stdout);
  37. fputs("\n", stdout);
  38. printf("not ok %d - %s\n", id, name);
  39. }
  40. int
  41. main(void)
  42. {
  43. int plan = 3;
  44. printf("1..%d\n", plan);
  45. t_sha512("empty",
  46. "",
  47. 0,
  48. "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"
  49. "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e");
  50. // https://web.archive.org/web/20130526224224/https://csrc.nist.gov/groups/STM/cavp/documents/shs/sha512-384-512.pdf
  51. t_sha512("abc",
  52. "abc",
  53. 3,
  54. "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a"
  55. "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f");
  56. // clang-format off
  57. t_sha512("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
  58. "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
  59. 112,
  60. "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018"
  61. "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909");
  62. // clang-format on
  63. assert(counter == plan);
  64. return err;
  65. }