Class: CookieMonster::Encryption

Inherits:
Base
  • Object
show all
Defined in:
lib/cookie_monster/encryption.rb

Defined Under Namespace

Classes: PasswordInvalid

Instance Method Summary collapse

Constructor Details

#initialize(payload) ⇒ Encryption

Returns a new instance of Encryption.



3
4
5
6
7
8
# File 'lib/cookie_monster/encryption.rb', line 3

def initialize(payload)
  @aes = ::OpenSSL::Cipher::Cipher.new(configuration.cipher_type)
  @aes.padding = 1
  @key = Digest::SHA256.digest(configuration.key)
  @payload = payload
end

Instance Method Details

#decryptObject



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/cookie_monster/encryption.rb', line 19

def decrypt
  payload = Base64.decode64 @payload
  iv, payload = payload.split(':', 2)
  @aes.decrypt
  @aes.iv = iv
  @aes.key = @key
  decrypted = @aes.update(payload) + @aes.final
  json_parsed_payload decrypted
rescue OpenSSL::Cipher::CipherError
  raise PasswordInvalid, "Password incorrect!"
end

#encryptObject



10
11
12
13
14
15
16
17
# File 'lib/cookie_monster/encryption.rb', line 10

def encrypt
  iv = configuration.iv
  @aes.encrypt
  @aes.iv = iv
  @aes.key = @key
  encrypted = iv + ':' + @aes.update(json_serialized_payload) + @aes.final
  Base64.encode64 encrypted
end