data.rb 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. module SecureMailing::PGP::Tool::Data
  3. extend ActiveSupport::Concern
  4. include SecureMailing::PGP::Tool::Exec
  5. included do # rubocop:disable Metrics/BlockLength
  6. def encrypt(data, recipients)
  7. options = [
  8. '--armor',
  9. '--trust-model', 'always'
  10. ]
  11. options += recipients.map { |recipient| ['--recipient', recipient] }.flatten
  12. gpg('encrypt', options:, stdin: data)
  13. end
  14. def decrypt(data, passphrase, skip_verify: false)
  15. options = [
  16. '--trust-model', 'always',
  17. ]
  18. options << '--skip-verify' if skip_verify
  19. result = gpg('decrypt', options:, stdin: data, passphrase: passphrase)
  20. error_algorithm!(result.stderr)
  21. result
  22. end
  23. def sign(data, fingerprint, passphrase)
  24. options = [
  25. '--armor',
  26. '--detach-sign',
  27. '--trust-model', 'always',
  28. '--default-key', fingerprint
  29. ]
  30. gpg('sign', options:, stdin: data, passphrase: passphrase)
  31. end
  32. def verify(data, signature: nil)
  33. options = [
  34. '--trust-model', 'always',
  35. ]
  36. return verify_detached_signature(options, data, signature) if signature.present?
  37. gpg('verify', options:, stdin: data)
  38. end
  39. private
  40. def verify_detached_signature(options, data, signature)
  41. data_file = Tempfile.new('data')
  42. signature_file = Tempfile.new('signature')
  43. begin
  44. data_file.write(data)
  45. data_file.close
  46. signature_file.write(signature)
  47. signature_file.close
  48. gpg('verify', options:, arguments: [signature_file.path, data_file.path])
  49. ensure
  50. data_file.unlink
  51. signature_file.unlink
  52. end
  53. end
  54. end
  55. end