Class: Prefab::Encryption

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

Constant Summary collapse

CIPHER_TYPE =

32/12

"aes-256-gcm"
SEPARATOR =
"--"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key_string_hex) ⇒ Encryption

Returns a new instance of Encryption.



17
18
19
# File 'lib/prefab/encryption.rb', line 17

def initialize(key_string_hex)
  @key = [key_string_hex].pack("H*")
end

Class Method Details

.generate_new_hex_keyObject

Hexadecimal format ensures that generated keys are representable with plain text

To convert back to the original string with the desired length:

[ value ].pack("H*")


13
14
15
# File 'lib/prefab/encryption.rb', line 13

def self.generate_new_hex_key
  generate_random_key.unpack("H*")[0]
end

Instance Method Details

#decrypt(encrypted_string) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/prefab/encryption.rb', line 40

def decrypt(encrypted_string)
  unpacked_parts = encrypted_string.split(SEPARATOR).map { |p| [p].pack("H*") }

  cipher = OpenSSL::Cipher.new(CIPHER_TYPE)
  cipher.decrypt
  cipher.key = @key
  cipher.iv = unpacked_parts[1]
  cipher.auth_tag = unpacked_parts[2]

  # and decrypt it
  decrypted = cipher.update(unpacked_parts[0])
  decrypted << cipher.final
  decrypted
end

#encrypt(clear_text) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/prefab/encryption.rb', line 21

def encrypt(clear_text)
  cipher = OpenSSL::Cipher.new(CIPHER_TYPE)
  cipher.encrypt
  iv = cipher.random_iv

  # load them into the cipher
  cipher.key = @key
  cipher.iv = iv
  cipher.auth_data = ""

  # encrypt the message
  encrypted = cipher.update(clear_text)
  encrypted << cipher.final
  tag = cipher.auth_tag

  # pack and join
  [encrypted, iv, tag].map { |p| p.unpack("H*")[0] }.join(SEPARATOR)
end