Class: DocVault::Encryption

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

Constant Summary collapse

ALGORITHM =
"AES-256-GCM"
IV_SIZE =
12
AUTH_TAG_SIZE =
16

Class Method Summary collapse

Class Method Details

.decrypt(encrypted_data, key) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/doc_vault/encryption.rb', line 30

def self.decrypt(encrypted_data, key)
  combined = Base64.strict_decode64(encrypted_data)

  cipher = OpenSSL::Cipher.new(ALGORITHM)
  cipher.decrypt

  salt = combined[0, 16]
  iv = combined[16, IV_SIZE]
  auth_tag = combined[16 + IV_SIZE, AUTH_TAG_SIZE]
  encrypted = combined[16 + IV_SIZE + AUTH_TAG_SIZE..]

  derived_key = OpenSSL::PKCS5.pbkdf2_hmac(key, salt, 100_000, 32, OpenSSL::Digest.new("SHA256"))
  cipher.key = derived_key
  cipher.iv = iv
  cipher.auth_tag = auth_tag

  cipher.update(encrypted) + cipher.final
rescue OpenSSL::Cipher::CipherError, ArgumentError
  raise EncryptionError, "Decryption failed"
end

.encrypt(data, key) ⇒ Object



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

def self.encrypt(data, key)
  cipher = OpenSSL::Cipher.new(ALGORITHM)
  cipher.encrypt

  salt = OpenSSL::Random.random_bytes(16)
  derived_key = OpenSSL::PKCS5.pbkdf2_hmac(key, salt, 100_000, 32, OpenSSL::Digest.new("SHA256"))
  cipher.key = derived_key

  iv = cipher.random_iv
  encrypted = cipher.update(data) + cipher.final
  auth_tag = cipher.auth_tag

  combined = salt + iv + auth_tag + encrypted
  Base64.strict_encode64(combined)
rescue OpenSSL::Cipher::CipherError
  raise EncryptionError, "Encryption failed"
end