Class: SecureNative::Utils::EncryptionUtils

Inherits:
Object
  • Object
show all
Defined in:
lib/securenative/utils/encryption_utils.rb

Class Method Summary collapse

Class Method Details

.decrypt(cipher_text, secret_key) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/securenative/utils/encryption_utils.rb', line 32

def self.decrypt(cipher_text, secret_key)
  begin
    cipher = OpenSSL::Cipher.new('aes-256-cbc')
    cipher.decrypt
    raw_data = [cipher_text].pack('H*')
    cipher.iv = raw_data.slice(0, 16)
    cipher.key = padding_key(secret_key, 32)
    decrypted = JSON.parse(cipher.update(raw_data.slice(16, raw_data.length)) + cipher.final)

    SecureNative::ClientToken.new(decrypted['cid'], decrypted['vid'], decrypted['fp'])
  rescue StandardError
    SecureNative::ClientToken.new('', '', '')
  end
end

.encrypt(plain_text, secret_key) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/securenative/utils/encryption_utils.rb', line 19

def self.encrypt(plain_text, secret_key)
  begin
    cipher = OpenSSL::Cipher.new('aes-256-cbc')
    cipher.encrypt
    iv = cipher.random_iv
    cipher.key = padding_key(secret_key, 32)
    encrypted = cipher.update(plain_text) + cipher.final
    (iv + encrypted).unpack1('H*')
  rescue StandardError
    ''
  end
end

.padding_key(key, length) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/securenative/utils/encryption_utils.rb', line 6

def self.padding_key(key, length)
  if key.length == length
    key
  else
    if key.length > length
      key.slice(0, length)
    else
      (length - key.length).times { key << '0' }
      key
    end
  end
end