Module: ConnectClient::Security

Defined in:
lib/connect_client/security/filtered_key_generation.rb

Class Method Summary collapse

Class Method Details

.bin_to_hex(binary_string) ⇒ Object



33
34
35
# File 'lib/connect_client/security/filtered_key_generation.rb', line 33

def self.bin_to_hex(binary_string)
  binary_string.unpack("H*").first.to_s.upcase
end

.generate_filtered_key(key_json, master_key) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/connect_client/security/filtered_key_generation.rb', line 5

def self.generate_filtered_key(key_json, master_key)
  key = master_key
  key = Digest::SHA256.digest(key) if(key.kind_of?(String) && 32 != key.bytesize)
  aes = OpenSSL::Cipher.new('AES-256-CBC')
  iv = aes.random_iv
  aes.encrypt
  aes.key = key
  aes.iv = iv
  encrypted = aes.update(key_json) + aes.final

  "#{bin_to_hex(iv)}-#{bin_to_hex(encrypted)}"
end

.generate_key_json(filtered_key, master_key) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/connect_client/security/filtered_key_generation.rb', line 18

def self.generate_key_json(filtered_key, master_key)
  iv_and_data = filtered_key.split('-')      
  iv = hex_to_bin(iv_and_data[0])
  encrypted_key_json = hex_to_bin(iv_and_data[1])

  key = master_key
  key = Digest::SHA256.digest(key) if(key.kind_of?(String) && 32 != key.bytesize)
  iv = Digest::MD5.digest(iv) if(iv.kind_of?(String) && 16 != iv.bytesize)
  aes = OpenSSL::Cipher.new('AES-256-CBC')      
  aes.decrypt
  aes.key = key
  aes.iv = iv
  aes.update(encrypted_key_json) + aes.final
end

.hex_to_bin(hex_string) ⇒ Object



37
38
39
# File 'lib/connect_client/security/filtered_key_generation.rb', line 37

def self.hex_to_bin(hex_string)
  hex_string.scan(/../).map { |x| x.hex }.pack('c*')
end