Sha256: 114620b4f63ec78eadc68261abe49896a9e7e9ad1aacc19060ae890bdfdc8256

Contents?: true

Size: 1.34 KB

Versions: 11

Compression:

Stored size: 1.34 KB

Contents

# frozen_string_literal: true

module SecureNative
  module Utils
    class EncryptionUtils
      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

      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

      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
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
securenative-0.1.40 lib/securenative/utils/encryption_utils.rb
securenative-0.1.39 lib/securenative/utils/encryption_utils.rb
securenative-0.1.38 lib/securenative/utils/encryption_utils.rb
securenative-0.1.37 lib/securenative/utils/encryption_utils.rb
securenative-0.1.36 lib/securenative/utils/encryption_utils.rb
securenative-0.1.35 lib/securenative/utils/encryption_utils.rb
securenative-0.1.34 lib/securenative/utils/encryption_utils.rb
securenative-0.1.33 lib/securenative/utils/encryption_utils.rb
securenative-0.1.32 lib/securenative/utils/encryption_utils.rb
securenative-0.1.31 lib/securenative/utils/encryption_utils.rb
securenative-0.1.30 lib/securenative/utils/encryption_utils.rb