1
0

sha1_test.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * @build: gcc -o bin/sha1 unittest/sha1_test.c util/sha1.c -I. -Iutil
  3. *
  4. */
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <assert.h>
  9. #include "sha1.h"
  10. static void test() {
  11. unsigned char ch = '1';
  12. char sha1[41] = {0};
  13. hv_sha1_hex(&ch, 1, sha1, sizeof(sha1));
  14. assert(strcmp(sha1, "356a192b7913b04c54574d18c28d46e6395428ab") == 0);
  15. }
  16. int main(int argc, char* argv[]) {
  17. test();
  18. if (argc < 2) {
  19. printf("Usage: sha1 file\n");
  20. printf(" sha1 -s string\n");
  21. return -10;
  22. }
  23. char sha1[41] = {0};
  24. if (argc == 2) {
  25. const char* filepath = argv[1];
  26. FILE* fp = fopen(filepath, "rb");
  27. if (fp == NULL) {
  28. printf("Open file '%s' failed!\n", filepath);
  29. return -20;
  30. }
  31. fseek(fp, 0, SEEK_END);
  32. long filesize = ftell(fp);
  33. // printf("filesize=%ld\n", filesize);
  34. fseek(fp, 0, SEEK_SET);
  35. unsigned char* filebuf = (unsigned char*)malloc(filesize);
  36. size_t nread = fread(filebuf, 1, filesize, fp);
  37. assert(nread == filesize);
  38. hv_sha1_hex(filebuf, filesize, sha1, sizeof(sha1));
  39. free(filebuf);
  40. fclose(fp);
  41. }
  42. else if (argc == 3) {
  43. const char* flags = argv[1];
  44. if (flags[0] == '-' && flags[1] == 's') {
  45. hv_sha1_hex((unsigned char*)argv[2], strlen(argv[2]), sha1, sizeof(sha1));
  46. }
  47. else {
  48. printf("Unrecognized flags '%s'\n", flags);
  49. return -40;
  50. }
  51. }
  52. puts(sha1);
  53. return 0;
  54. }