module Tinypass::SecurityUtils

Constants

DELIM

Public Instance Methods

decrypt(key, data) click to toggle source
# File lib/tinypass/builder/security_utils.rb, line 23
def decrypt(key, data)
  cipher_text, hmac_text = data.split(DELIM)
  check_hmac!(key, cipher_text, hmac_text) if hmac_text
  key = prepare_key(key)
  cipher_text = url_desafe(cipher_text)

  cipher = OpenSSL::Cipher.new('AES-256-ECB')
  cipher.decrypt
  cipher.key = key
  cipher.update(cipher_text) + cipher.final
end
encrypt(key, data) click to toggle source
# File lib/tinypass/builder/security_utils.rb, line 10
def encrypt(key, data)
  original_key = key
  key = prepare_key(key)

  cipher = OpenSSL::Cipher.new('AES-256-ECB')
  cipher.encrypt
  cipher.key = key
  encrypted = cipher.update(data) + cipher.final

  safe = url_ensafe(encrypted)
  safe + DELIM + hash_hmac_sha256(original_key, safe)
end
hash_hmac_sha256(key, data) click to toggle source
# File lib/tinypass/builder/security_utils.rb, line 35
def hash_hmac_sha256(key, data)
  digest = OpenSSL::Digest::Digest.new('sha256')
  hmac = OpenSSL::HMAC.digest(digest, key, data)
  url_ensafe(hmac)
end

Private Instance Methods

check_hmac!(key, cipher_text, hmac_text) click to toggle source
# File lib/tinypass/builder/security_utils.rb, line 61
def check_hmac!(key, cipher_text, hmac_text)
  if hash_hmac_sha256(key, cipher_text) != hmac_text
    raise ArgumentError.new('Could not parse message invalid hmac')
  end
end
prepare_key(key) click to toggle source
# File lib/tinypass/builder/security_utils.rb, line 55
def prepare_key(key)
  key = key.slice(0, 32) if key.length > 32
  key = key.ljust(32, 'X') if key.length < 32
  key
end
url_desafe(data) click to toggle source
# File lib/tinypass/builder/security_utils.rb, line 49
def url_desafe(data)
  modulus = data.length % 4
  data << '=' * (4 - modulus) if modulus != 0
  Base64.urlsafe_decode64(data)
end
url_ensafe(data) click to toggle source
# File lib/tinypass/builder/security_utils.rb, line 43
def url_ensafe(data)
  base64 = Base64.urlsafe_encode64(data)
  base64.sub!(/(=+)$/, '')
  base64
end