hmac_file.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* LibTomCrypt, modular cryptographic library -- Tom St Denis
  2. *
  3. * LibTomCrypt is a library that provides various cryptographic
  4. * algorithms in a highly modular and flexible manner.
  5. *
  6. * The library is free for all purposes without any express
  7. * guarantee it works.
  8. *
  9. * Tom St Denis, [email protected], http://libtomcrypt.org
  10. */
  11. /* Submited by Dobes Vandermeer ([email protected]) */
  12. #include "mycrypt.h"
  13. #ifdef HMAC
  14. /* hmac_file added by Tom St Denis */
  15. int hmac_file(int hash, const char *fname,
  16. const unsigned char *key, unsigned long keylen,
  17. unsigned char *dst, unsigned long *dstlen)
  18. {
  19. #ifdef NO_FILE
  20. return CRYPT_NOP;
  21. #else
  22. hmac_state hmac;
  23. FILE *in;
  24. unsigned char buf[512];
  25. size_t x;
  26. int err;
  27. _ARGCHK(fname != NULL);
  28. _ARGCHK(key != NULL);
  29. _ARGCHK(dst != NULL);
  30. _ARGCHK(dstlen != NULL);
  31. if((err = hash_is_valid(hash)) != CRYPT_OK) {
  32. return err;
  33. }
  34. if ((err = hmac_init(&hmac, hash, key, keylen)) != CRYPT_OK) {
  35. return err;
  36. }
  37. in = fopen(fname, "rb");
  38. if (in == NULL) {
  39. return CRYPT_FILE_NOTFOUND;
  40. }
  41. /* process the file contents */
  42. do {
  43. x = fread(buf, 1, sizeof(buf), in);
  44. if ((err = hmac_process(&hmac, buf, (unsigned long)x)) != CRYPT_OK) {
  45. /* we don't trap this error since we're already returning an error! */
  46. fclose(in);
  47. return err;
  48. }
  49. } while (x == sizeof(buf));
  50. if (fclose(in) != 0) {
  51. return CRYPT_ERROR;
  52. }
  53. /* get final hmac */
  54. if ((err = hmac_done(&hmac, dst, dstlen)) != CRYPT_OK) {
  55. return err;
  56. }
  57. #ifdef CLEAN_STACK
  58. /* clear memory */
  59. zeromem(buf, sizeof(buf));
  60. #endif
  61. return CRYPT_OK;
  62. #endif
  63. }
  64. #endif