gpgme.c 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #include "src/gpgme.h"
  2. #include <gpgme.h>
  3. #include <stdio.h>
  4. int rgpgfs_gpgme_data_to_file(const char *path, gpgme_data_t data) {
  5. if (gpgme_data_seek(data, 0, SEEK_SET) != 0) {
  6. perror("rgpgfs_gpgme_data_to_file: failed to seek");
  7. return 1;
  8. }
  9. FILE *file = fopen(path, "wb");
  10. if (file == NULL) {
  11. perror("rgpgfs_gpgme_data_to_file: failed to open file");
  12. return 1;
  13. }
  14. ssize_t count;
  15. char buf[BUFSIZ];
  16. while ((count = gpgme_data_read(data, buf, BUFSIZ)) > 0) {
  17. if (fwrite(buf, 1, count, file) != count) {
  18. fprintf(stderr,
  19. "rgpgfs_gpgme_data_to_file: failed to write data to file");
  20. return 1;
  21. }
  22. }
  23. if (count != 0) {
  24. perror("rgpgfs_gpgme_data_to_file: failed to load data into buffer");
  25. return 1;
  26. }
  27. fclose(file);
  28. return 0;
  29. }
  30. int rgpgfs_gpgme_encrypt_data_to_file(gpgme_ctx_t gpgme_ctx,
  31. gpgme_key_t recip_keys[],
  32. gpgme_data_t plain_data,
  33. const char *cipher_path) {
  34. gpgme_data_t cipher_data;
  35. if (gpgme_data_new(&cipher_data) != GPG_ERR_NO_ERROR) {
  36. fprintf(stderr, "rgpgfs_gpgme_encrypt_data_to_file: failed to prepare "
  37. "cipher data container\n");
  38. return 1;
  39. }
  40. int result = 0;
  41. // list of recipients may implicitly include the default recipient
  42. // (GPGME_ENCRYPT_NO_ENCRYPT_TO)
  43. if (gpgme_op_encrypt(gpgme_ctx, recip_keys, 0, plain_data, cipher_data) !=
  44. GPG_ERR_NO_ERROR) {
  45. fprintf(stderr, "rgpgfs_gpgme_encrypt_data_to_file: failed to encrypt\n");
  46. result = 1;
  47. } else if (rgpgfs_gpgme_data_to_file(cipher_path, cipher_data)) {
  48. fprintf(stderr, "rgpgfs_gpgme_encrypt_data_to_file: failed to write cipher "
  49. "data to disk\n");
  50. result = 1;
  51. }
  52. gpgme_data_release(cipher_data);
  53. return result;
  54. }
  55. int rgpgfs_gpgme_encrypt_file_to_file(gpgme_ctx_t gpgme_ctx,
  56. gpgme_key_t recip_keys[],
  57. const char *plain_path,
  58. const char *cipher_path) {
  59. gpgme_data_t plain_data;
  60. gpgme_error_t gpgme_read_err =
  61. gpgme_data_new_from_file(&plain_data, plain_path, 1);
  62. if (gpgme_read_err != GPG_ERR_NO_ERROR) {
  63. fprintf(stderr, "%s: failed to read file %s: %s (%d)\n", __func__,
  64. plain_path, gpg_strerror(gpgme_read_err), gpgme_read_err);
  65. return 1;
  66. }
  67. int result = rgpgfs_gpgme_encrypt_data_to_file(gpgme_ctx, recip_keys,
  68. plain_data, cipher_path);
  69. gpgme_data_release(plain_data);
  70. return result;
  71. }