Class: CryptKeeperProviders::Aes

Inherits:
Object
  • Object
show all
Defined in:
lib/crypt_keeper_providers/aes.rb

Constant Summary collapse

SEPARATOR =
":crypt_keeper:"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Aes

Public: Initializes the class

options - A hash of options. :key is required


18
19
20
21
22
23
24
25
26
27
# File 'lib/crypt_keeper_providers/aes.rb', line 18

def initialize(options = {})
  @aes         = ::OpenSSL::Cipher.new("AES-256-CBC")
  @aes.padding = 1

  key = options.fetch(:key) do
    raise ArgumentError, "Missing :key"
  end

  @key = Digest::SHA256.digest(key)
end

Instance Attribute Details

#aesObject

Public: An instance of OpenSSL::Cipher::Cipher



13
14
15
# File 'lib/crypt_keeper_providers/aes.rb', line 13

def aes
  @aes
end

#keyObject

Public: The encryption key



10
11
12
# File 'lib/crypt_keeper_providers/aes.rb', line 10

def key
  @key
end

Instance Method Details

#decrypt(value) ⇒ Object

Public: Decrypt a string

Returns a string



44
45
46
47
48
49
50
51
# File 'lib/crypt_keeper_providers/aes.rb', line 44

def decrypt(value)
  return if value.nil?
  iv, value = Base64::decode64(value.to_s).split(SEPARATOR)
  aes.decrypt
  aes.key = key
  aes.iv  = iv
  aes.update(value) + aes.final
end

#encrypt(value) ⇒ Object

Public: Encrypt a string

Returns a string



32
33
34
35
36
37
38
39
# File 'lib/crypt_keeper_providers/aes.rb', line 32

def encrypt(value)
  return if value.nil?
  aes.encrypt
  aes.key = key
  iv      = aes.random_iv
  aes.iv  = iv
  Base64::encode64("#{iv}#{SEPARATOR}#{aes.update(value.to_s) + aes.final}")
end