Sha256: ecbdb098f34dd41526e7970ecdbcd405b166821e64933fae53dac8abcff0fc32

Contents?: true

Size: 1.5 KB

Versions: 1

Compression:

Stored size: 1.5 KB

Contents

module Xml
  module Kit
    # {include:file:spec/saml/xml_decryption_spec.rb}
    class Decryption
      # The list of private keys to use to attempt to decrypt the document.
      attr_reader :private_keys

      def initialize(private_keys:)
        @private_keys = private_keys
      end

      # Decrypts an EncryptedData section of an XML document.
      #
      # @param data [Hash] the XML document converted to a [Hash] using Hash.from_xml.
      def decrypt(data)
        encrypted_data = data['EncryptedData']
        symmetric_key = symmetric_key_from(encrypted_data)
        cipher_text = Base64.decode64(encrypted_data["CipherData"]["CipherValue"])
        to_plaintext(cipher_text, symmetric_key, encrypted_data["EncryptionMethod"]['Algorithm'])
      end

      private

      def symmetric_key_from(encrypted_data)
        encrypted_key = encrypted_data['KeyInfo']['EncryptedKey']
        cipher_text = Base64.decode64(encrypted_key['CipherData']['CipherValue'])
        attempts = private_keys.count
        private_keys.each do |private_key|
          begin
            attempts -= 1
            return to_plaintext(cipher_text, private_key, encrypted_key["EncryptionMethod"]['Algorithm'])
          rescue OpenSSL::PKey::RSAError => error
            ::Xml::Kit.logger.error(error)
            raise if attempts.zero?
          end
        end
      end

      def to_plaintext(cipher_text, symmetric_key, algorithm)
        Crypto.decryptor_for(algorithm, symmetric_key).decrypt(cipher_text)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
xml-kit-0.1.0 lib/xml/kit/decryption.rb