Class: Heroku::Bouncer::Lockbox

Inherits:
BasicObject
Defined in:
lib/heroku/bouncer/lockbox.rb

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ Lockbox

Returns a new instance of Lockbox.



5
6
7
# File 'lib/heroku/bouncer/lockbox.rb', line 5

def initialize(key)
  @key = key
end

Instance Method Details

#lock(str) ⇒ Object



9
10
11
12
13
14
15
# File 'lib/heroku/bouncer/lockbox.rb', line 9

def lock(str)
  aes = cipher.encrypt
  aes.key = @key.size > 32 ? @key[0..31] : @key
  iv = ::OpenSSL::Random.random_bytes(aes.iv_len)
  aes.iv = iv
  [iv + (aes.update(str) << aes.final)].pack('m0')
end

#unlock(str) ⇒ Object

decrypts string. returns nil if an error occurs

returns nil if openssl raises an error during decryption (data manipulation, key change, implementation change), or if the text to decrypt is too short to possibly be good aes data.



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/heroku/bouncer/lockbox.rb', line 22

def unlock(str)
  str = str.unpack('m0').first
  aes = cipher.decrypt
  aes.key = @key.size > 32 ? @key[0..31] : @key
  iv = str[0, aes.iv_len]
  aes.iv = iv
  crypted_text = str[aes.iv_len..-1]
  return nil if crypted_text.nil? || iv.nil?
  aes.update(crypted_text) << aes.final
rescue
  nil
end