gcm_file.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
  2. /* SPDX-License-Identifier: Unlicense */
  3. #include "tomcrypt.h"
  4. /**
  5. @file gcm_file.c
  6. GCM process a file, Steffen Jaeckel
  7. */
  8. #ifdef LTC_GCM_MODE
  9. #ifndef LTC_NO_FILE
  10. /**
  11. Process a file.
  12. c.f. gcm_filehandle() for basic documentation.
  13. It is possible, that in error-cases the 'out' file
  14. will be created and after the error occurred it will
  15. be removed again.
  16. @param cipher Index of cipher to use
  17. @param key The secret key
  18. @param keylen The length of the secret key
  19. @param IV The initial vector
  20. @param IVlen The length of the initial vector
  21. @param adata The additional authentication data (header)
  22. @param adatalen The length of the adata
  23. @param in The input file
  24. @param out The output file
  25. @param taglen The MAC tag length
  26. @param direction Encrypt or Decrypt mode (GCM_ENCRYPT or GCM_DECRYPT)
  27. @param res [out] Result of the operation, 1==valid, 0==invalid
  28. @return CRYPT_OK on success
  29. */
  30. int gcm_file( int cipher,
  31. const unsigned char *key, unsigned long keylen,
  32. const unsigned char *IV, unsigned long IVlen,
  33. const unsigned char *adata, unsigned long adatalen,
  34. const char *in,
  35. const char *out,
  36. unsigned long taglen,
  37. int direction,
  38. int *res)
  39. {
  40. int err;
  41. FILE *f_in = NULL, *f_out = NULL;
  42. LTC_ARGCHK(in != NULL);
  43. LTC_ARGCHK(out != NULL);
  44. LTC_ARGCHK(res != NULL);
  45. *res = 0;
  46. f_in = fopen(in, "rb");
  47. if (f_in == NULL) {
  48. err = CRYPT_FILE_NOTFOUND;
  49. goto LBL_ERR;
  50. }
  51. f_out = fopen(out, "w+b");
  52. if (f_out == NULL) {
  53. err = CRYPT_FILE_NOTFOUND;
  54. goto LBL_ERR;
  55. }
  56. err = gcm_filehandle(cipher, key, keylen, IV, IVlen, adata, adatalen, f_in, f_out, taglen, direction, res);
  57. LBL_ERR:
  58. if (f_out != NULL && fclose(f_out) != 0) {
  59. err = CRYPT_ERROR;
  60. }
  61. if (*res != 1) {
  62. remove(out);
  63. }
  64. if (f_in != NULL && fclose(f_in) != 0) {
  65. err = CRYPT_ERROR;
  66. }
  67. return err;
  68. }
  69. #endif
  70. #endif