1
0

md5_test.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * @build: gcc -o bin/md5 unittest/md5_test.c util/md5.c -I. -Iutil
  3. *
  4. */
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <assert.h>
  9. #include "md5.h"
  10. static void test() {
  11. unsigned char ch = '1';
  12. char md5[33] = {0};
  13. hv_md5_hex(&ch, 1, md5, sizeof(md5));
  14. assert(strcmp(md5, "c4ca4238a0b923820dcc509a6f75849b") == 0);
  15. }
  16. int main(int argc, char* argv[]) {
  17. test();
  18. if (argc < 2) {
  19. printf("Usage: md5 file\n");
  20. printf(" md5 -s string\n");
  21. return -10;
  22. }
  23. char md5[33] = {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_md5_hex(filebuf, filesize, md5, sizeof(md5));
  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_md5_hex((unsigned char*)argv[2], strlen(argv[2]), md5, sizeof(md5));
  46. }
  47. else {
  48. printf("Unrecognized flags '%s'\n", flags);
  49. return -40;
  50. }
  51. }
  52. puts(md5);
  53. return 0;
  54. }