Module: Encrypt

Defined in:
lib/util/encrypt-data.rb

Class Method Summary collapse

Class Method Details

.encrypt_with_aes_rsa(data, public_key, is_json) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/util/encrypt-data.rb', line 11

def self.encrypt_with_aes_rsa(data, public_key, is_json)
  key = generate_random_bytes(32) # Generate a 256-bit random key for AES encryption
  iv = generate_random_bytes(16) # Generate a 128-bit random initialization vector for AES encryption

  cipher = OpenSSL::Cipher.new('AES-256-CBC')
  cipher.encrypt
  cipher.key = key
  cipher.iv = iv

  encrypted = if is_json
                cipher.update(data.to_json) + cipher.final
              else
                cipher.update(data) + cipher.final
              end

  encrypted_data = Base64.strict_encode64(encrypted)

  ####
  rsa_public_key = OpenSSL::PKey::RSA.new(public_key)
  encrypted_key = rsa_encrypt(key, rsa_public_key)
  encrypted_iv = rsa_encrypt(iv, rsa_public_key)

  { encrypted_data: encrypted_data, encrypted_key: encrypted_key, encrypted_iv: encrypted_iv }
end

.generate_random_bytes(length) ⇒ Object



7
8
9
# File 'lib/util/encrypt-data.rb', line 7

def self.generate_random_bytes(length)
  OpenSSL::Random.random_bytes(length)
end

.rsa_encrypt(data, public_key) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/util/encrypt-data.rb', line 36

def self.rsa_encrypt(data, public_key)
  # Define the encryption parameters
  label = ''

  md = OpenSSL::Digest::SHA256
  cipher_text = public_key.public_encrypt_oaep(data, label, md, md)

  return Base64.strict_encode64(cipher_text)
end