class Xml::Kit::Crypto::SymmetricCipher

Constants

ALGORITHMS
DEFAULT_ALGORITHM

Attributes

algorithm[R]
key[R]
padding[R]

Public Class Methods

matches?(algorithm) click to toggle source
# File lib/xml/kit/crypto/symmetric_cipher.rb, line 23
def self.matches?(algorithm)
  ALGORITHMS[algorithm]
end
new(algorithm = DEFAULT_ALGORITHM, key = nil, padding = nil) click to toggle source
# File lib/xml/kit/crypto/symmetric_cipher.rb, line 17
def initialize(algorithm = DEFAULT_ALGORITHM, key = nil, padding = nil)
  @algorithm = algorithm
  @key = key || cipher.random_key
  @padding = padding
end

Public Instance Methods

decrypt(cipher_text) click to toggle source
# File lib/xml/kit/crypto/symmetric_cipher.rb, line 33
def decrypt(cipher_text)
  bytes = cipher_text.bytes
  result = default_decrypt(
    bytes[0...cipher.iv_len],
    bytes[cipher.iv_len..-1]
  )
  return result if padding.nil?

  padding_size = result.bytes.last
  result[0...-padding_size]
end
encrypt(plain_text) click to toggle source
# File lib/xml/kit/crypto/symmetric_cipher.rb, line 27
def encrypt(plain_text)
  cipher.encrypt
  cipher.key = @key
  cipher.random_iv + cipher.update(plain_text) + cipher.final
end
to_s() click to toggle source
# File lib/xml/kit/crypto/symmetric_cipher.rb, line 45
def to_s
  algorithm
end

Protected Instance Methods

default_decrypt(initialization_vector, data) click to toggle source
# File lib/xml/kit/crypto/symmetric_cipher.rb, line 51
def default_decrypt(initialization_vector, data)
  cipher.decrypt
  apply_padding_to(cipher)
  cipher.key = @key
  cipher.iv = initialization_vector.pack('c*')
  cipher.update(data.pack('c*')) << cipher.final
end

Private Instance Methods

apply_padding_to(cipher) click to toggle source
# File lib/xml/kit/crypto/symmetric_cipher.rb, line 65
def apply_padding_to(cipher)
  cipher.padding = padding unless padding.nil?
end
cipher() click to toggle source
# File lib/xml/kit/crypto/symmetric_cipher.rb, line 61
def cipher
  @cipher ||= OpenSSL::Cipher.new(ALGORITHMS[algorithm])
end