Sha256: 2ebefb7036390c1f6a18e31d2cda7a457e5e93aa29a281f3b4fd9b467086c36b

Contents?: true

Size: 1.69 KB

Versions: 1

Compression:

Stored size: 1.69 KB

Contents

# frozen_string_literal: true

module Xml
  module Kit
    module Crypto
      class SymmetricCipher
        DEFAULT_ALGORITHM = "#{::Xml::Kit::Namespaces::XMLENC}aes256-cbc".freeze
        ALGORITHMS = {
          "#{::Xml::Kit::Namespaces::XMLENC}tripledes-cbc" => 'DES-EDE3-CBC',
          "#{::Xml::Kit::Namespaces::XMLENC}aes128-cbc" => 'AES-128-CBC',
          "#{::Xml::Kit::Namespaces::XMLENC}aes192-cbc" => 'AES-192-CBC',
          "#{::Xml::Kit::Namespaces::XMLENC}aes256-cbc" => 'AES-256-CBC',
        }.freeze

        attr_reader :algorithm, :key, :padding

        def initialize(algorithm, key = nil, padding = nil)
          @algorithm = algorithm
          @key = key || cipher.random_key
          @padding = padding
        end

        def self.matches?(algorithm)
          ALGORITHMS[algorithm]
        end

        def encrypt(plain_text)
          cipher.encrypt
          cipher.key = @key
          cipher.random_iv + cipher.update(plain_text) + cipher.final
        end

        def decrypt(cipher_text)
          result = default_decrypt(
            cipher_text[0...cipher.iv_len],
            cipher_text[cipher.iv_len..-1]
          )
          return result if padding.nil?

          padding_size = result.bytes.last
          result[0...-padding_size]
        end

        protected

        def default_decrypt(initialization_vector, data)
          cipher.decrypt
          cipher.padding = padding unless padding.nil?
          cipher.key = @key
          cipher.iv = initialization_vector
          cipher.update(data) << cipher.final
        end

        private

        def cipher
          @cipher ||= OpenSSL::Cipher.new(ALGORITHMS[algorithm])
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
xml-kit-0.2.0 lib/xml/kit/crypto/symmetric_cipher.rb