Class: Portunus::Encrypters::OpenSslAes

Inherits:
Object
  • Object
show all
Defined in:
lib/portunus/encrypters/open_ssl_aes.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key:, value:) ⇒ OpenSslAes

Returns a new instance of OpenSslAes.



18
19
20
21
# File 'lib/portunus/encrypters/open_ssl_aes.rb', line 18

def initialize(key:, value:)
  @key = Base64.strict_decode64(key)
  @value = value
end

Class Method Details

.decrypt(key:, value:) ⇒ Object



14
15
16
# File 'lib/portunus/encrypters/open_ssl_aes.rb', line 14

def self.decrypt(key:, value:)
  new(key: key, value: value).decrypt
end

.encrypt(key:, value:) ⇒ Object



4
5
6
# File 'lib/portunus/encrypters/open_ssl_aes.rb', line 4

def self.encrypt(key:, value:)
  new(key: key, value: value).encrypt
end

.generate_keyObject



8
9
10
11
12
# File 'lib/portunus/encrypters/open_ssl_aes.rb', line 8

def self.generate_key
  cipher = OpenSSL::Cipher::AES256.new :CBC
  cipher.encrypt
  Base64.strict_encode64(cipher.random_key)
end

Instance Method Details

#decryptObject



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/portunus/encrypters/open_ssl_aes.rb', line 39

def decrypt
  iv, encrypted_text = value.split("$")

  decipher = OpenSSL::Cipher::AES256.new :CBC
  decipher.decrypt

  decipher.iv = Base64.strict_decode64(iv) # previously saved
  decipher.key = key

  output = decipher.update(Base64.strict_decode64(encrypted_text)) + decipher.final

  output
end

#encryptObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/portunus/encrypters/open_ssl_aes.rb', line 23

def encrypt
  cipher = OpenSSL::Cipher::AES256.new :CBC
  cipher.encrypt
  iv = cipher.random_iv

  cipher.key = key
  cipher.iv = iv

  encrypted_output = cipher.update(value) + cipher.final

  [
    Base64.strict_encode64(iv),
    Base64.strict_encode64(encrypted_output)
  ].join("$")
end