1
0

md5_test.c 1.4 KB

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