Class: SymmetricEncryption::Key

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key: :random, iv: :random, cipher_name: 'aes-256-cbc') ⇒ Key

Returns a new instance of Key.



6
7
8
9
10
# File 'lib/symmetric_encryption/key.rb', line 6

def initialize(key: :random, iv: :random, cipher_name: 'aes-256-cbc')
  @key         = key == :random ? ::OpenSSL::Cipher.new(cipher_name).random_key : key
  @iv          = iv == :random ? ::OpenSSL::Cipher.new(cipher_name).random_iv : iv
  @cipher_name = cipher_name
end

Instance Attribute Details

#cipher_nameObject (readonly)

Returns the value of attribute cipher_name.



4
5
6
# File 'lib/symmetric_encryption/key.rb', line 4

def cipher_name
  @cipher_name
end

#ivObject (readonly)

Returns the value of attribute iv.



4
5
6
# File 'lib/symmetric_encryption/key.rb', line 4

def iv
  @iv
end

#keyObject (readonly)

Returns the value of attribute key.



4
5
6
# File 'lib/symmetric_encryption/key.rb', line 4

def key
  @key
end

Instance Method Details

#decrypt(encrypted_string) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/symmetric_encryption/key.rb', line 28

def decrypt(encrypted_string)
  return if encrypted_string.nil?

  encrypted_string = encrypted_string.to_s
  encrypted_string.force_encoding(SymmetricEncryption::BINARY_ENCODING)
  return encrypted_string if encrypted_string.empty?

  # Creates a new OpenSSL::Cipher with every call so that this key instance is thread-safe.
  openssl_cipher = ::OpenSSL::Cipher.new(cipher_name)
  openssl_cipher.decrypt
  openssl_cipher.key = key
  openssl_cipher.iv  = iv

  result = openssl_cipher.update(encrypted_string)
  result << openssl_cipher.final
end

#encrypt(string) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/symmetric_encryption/key.rb', line 12

def encrypt(string)
  return if string.nil?

  string = string.to_s
  return string if string.empty?

  # Creates a new OpenSSL::Cipher with every call so that this key instance is thread-safe.
  openssl_cipher = ::OpenSSL::Cipher.new(cipher_name)
  openssl_cipher.encrypt
  openssl_cipher.key = key
  openssl_cipher.iv  = iv

  result = openssl_cipher.update(string)
  result << openssl_cipher.final
end