Class: Infosimples::Data::SymmetricEncryption

Inherits:
Object
  • Object
show all
Defined in:
lib/infosimples/data/symmetric_encryption.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ SymmetricEncryption

Returns a new instance of SymmetricEncryption.



4
5
6
7
# File 'lib/infosimples/data/symmetric_encryption.rb', line 4

def initialize(key)
  fail("INVALID KEY SIZE: #{key}") if key.size < 32
  self.key = key[0, 32]
end

Instance Attribute Details

#keyObject

Returns the value of attribute key.



3
4
5
# File 'lib/infosimples/data/symmetric_encryption.rb', line 3

def key
  @key
end

Instance Method Details

#decrypt(data, from_base64 = true) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/infosimples/data/symmetric_encryption.rb', line 17

def decrypt(data, from_base64=true)
  data = Base64.decode64(data) if from_base64
  aes = OpenSSL::Cipher.new('AES-256-CBC')
  aes.decrypt
  aes.key = Digest::SHA256.digest(key)
  aes.update(data) + aes.final
end

#encrypt(data, to_base64 = true) ⇒ Object



9
10
11
12
13
14
15
# File 'lib/infosimples/data/symmetric_encryption.rb', line 9

def encrypt(data, to_base64=true)
  aes = OpenSSL::Cipher.new('AES-256-CBC')
  aes.encrypt
  aes.key = Digest::SHA256.digest(key)
  encrypted_data = aes.update(data) + aes.final
  to_base64 ? Base64.encode64(encrypted_data) : encrypted_data
end