logo

utils-std

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

sha256.c (1807B)


  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/sha256.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_sha256(const char *name,
  14. const void *data,
  15. size_t datalen,
  16. const char expected[SHA256_DIGEST_LENGTH * 2])
  17. {
  18. int id = ++counter;
  19. struct sha256 ctx;
  20. sha256_init(&ctx);
  21. sha256_update(&ctx, data, datalen);
  22. uint8_t res[SHA256_DIGEST_LENGTH] = "";
  23. sha256_sum(&ctx, res);
  24. char got[SHA256_DIGEST_LENGTH * 2] = "";
  25. bytes2hex(res, sizeof(res), got, sizeof(got));
  26. if(memcmp(expected, got, SHA256_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, SHA256_DIGEST_LENGTH * 2, 1, stdout);
  34. fputs("\n", stdout);
  35. fputs("# Got: ", stdout);
  36. fwrite(got, SHA256_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_sha256("empty", "", 0, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
  46. // https://web.archive.org/web/20130526224224/https://csrc.nist.gov/groups/STM/cavp/documents/shs/sha256-384-512.pdf
  47. t_sha256("abc", "abc", 3, "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
  48. t_sha256("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
  49. "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
  50. 56,
  51. "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1");
  52. assert(counter == plan);
  53. return err;
  54. }