sha256.c 1018 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #include <rtthread.h>
  2. #include <assert.h>
  3. #include <errno.h>
  4. #include <limits.h>
  5. #include <stdio.h>
  6. #include <stdint.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #include "sodium.h"
  10. // Python equivalent
  11. // hashlib.sha256(b'testing').hexdigest()
  12. // `cf80cd8aed482d5d1527d7dc72fceff84e6326592848447d2dc0b0e87dfc9a90`
  13. static unsigned char x[] = "testing";
  14. static unsigned char h[crypto_hash_sha256_BYTES];
  15. int sha256(int argc, char* argv[])
  16. {
  17. size_t i;
  18. // Hash function
  19. if (argc == 2) {
  20. crypto_hash_sha256(h, (const unsigned char *) argv[1], strlen(argv[1]));
  21. printf("sha256(\"%s\") = ", argv[1]);
  22. }
  23. else {
  24. printf("Usage: %s testing\n", argv[0]);
  25. crypto_hash_sha256(h, x, sizeof(x) - 1U); // remove the ending '\0'
  26. printf("sha256(\"%s\") = ", x);
  27. }
  28. // Print the hash result
  29. for (i = 0; i < crypto_hash_sha256_BYTES; ++i) {
  30. printf("%02x", (unsigned int) h[i]);
  31. }
  32. printf("\n");
  33. return 0;
  34. }
  35. MSH_CMD_EXPORT(sha256, sha256)