logo

utils-std

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

sha1.c (1531B)


  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/sha1.h"
  6. #include "../lib/strconv.h"
  7. #include <assert.h>
  8. #include <stdio.h> // printf
  9. #include <string.h> // memcmp, memset
  10. int counter = 0;
  11. int err = 0;
  12. static void
  13. t_sha1(const char *name,
  14. const void *data,
  15. size_t datalen,
  16. const char expected[SHA1_DIGEST_LENGTH * 2])
  17. {
  18. int id = ++counter;
  19. struct sha1 ctx;
  20. sha1_init(&ctx);
  21. sha1_update(&ctx, data, datalen);
  22. uint8_t res[SHA1_DIGEST_LENGTH] = "";
  23. sha1_sum(&ctx, res);
  24. char got[SHA1_DIGEST_LENGTH * 2] = "";
  25. bytes2hex(res, sizeof(res), got, sizeof(got));
  26. if(memcmp(expected, got, SHA1_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, SHA1_DIGEST_LENGTH * 2, 1, stdout);
  34. fputs("\n", stdout);
  35. fputs("# Got: ", stdout);
  36. fwrite(got, SHA1_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. uint8_t million_a[1000000];
  46. memset(million_a, 'a', 1000000);
  47. t_sha1("empty", "", 0, "da39a3ee5e6b4b0d3255bfef95601890afd80709");
  48. t_sha1("abc", "abc", 3, "a9993e364706816aba3e25717850c26c9cd0d89d");
  49. t_sha1("million_a", million_a, 1000000, "34aa973cd4c4daa4f61eeb2bdbad27316534016f");
  50. assert(counter == plan);
  51. return err;
  52. }