Sha256: 3168d2325b4f109581514247836c14382914dc08f8a7a956e1894160d978aa7d

Contents?: true

Size: 1.34 KB

Versions: 3

Compression:

Stored size: 1.34 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 :key

        def initialize(algorithm, key = nil)
          @algorithm = algorithm
          @key = key || cipher.random_key
        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)
          cipher.decrypt
          iv = cipher_text[0..cipher.iv_len - 1]
          data = cipher_text[cipher.iv_len..-1]
          # cipher.padding = 0
          cipher.key = @key
          cipher.iv = iv
          cipher.update(data) + cipher.final
        end

        private

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

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
xml-kit-0.1.14 lib/xml/kit/crypto/symmetric_cipher.rb
xml-kit-0.1.13 lib/xml/kit/crypto/symmetric_cipher.rb
xml-kit-0.1.12 lib/xml/kit/crypto/symmetric_cipher.rb