private_key.rb 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class SecureMailing::SMIME::PrivateKey
  3. attr_reader :uid, :pem, :secret
  4. def self.read(pem, secret)
  5. begin
  6. new(pem, secret)
  7. rescue OpenSSL::PKey::PKeyError
  8. raise Exceptions::UnprocessableEntity, __('The private key is not valid for S/MIME usage. Please check the key format and the secret.')
  9. end
  10. end
  11. def initialize(pem, secret)
  12. @key = OpenSSL::PKey.read(pem, secret)
  13. @uid = determine_uid
  14. @pem = @key.to_pem
  15. @secret = secret
  16. end
  17. def valid_smime_private_key?
  18. return false if !rsa? && !ec?
  19. true
  20. end
  21. def valid_smime_private_key!
  22. return if valid_smime_private_key?
  23. message = __('The private key is not valid for S/MIME usage. Please check the key cryptographic algorithm.')
  24. Rails.logger.error { "SMIME::PrivateKey: #{message}" }
  25. Rails.logger.error { "SMIME::PrivateKey:\n #{@key.to_pem}" }
  26. raise Exceptions::UnprocessableEntity, message
  27. end
  28. def rsa?
  29. @key.class.name.end_with?('RSA')
  30. end
  31. def ec?
  32. @key.class.name.end_with?('EC')
  33. end
  34. private
  35. def determine_uid
  36. return @key.public_key.n.to_s(16) if rsa?
  37. OpenSSL::Digest.new('SHA1', @key.public_to_der).to_s
  38. end
  39. end