Module: Tokenifier::Encrypt

Included in:
Tokenifier
Defined in:
lib/tokenifier/encrypt.rb

Instance Method Summary collapse

Instance Method Details

#encrypt(data, options = {}) ⇒ Object

Raises:



12
13
14
15
16
17
18
19
20
# File 'lib/tokenifier/encrypt.rb', line 12

def encrypt(data, options = {})

  raise Tokenifier::Error, "DATA should not be nil" if data.nil?
  raise Tokenifier::Error, "DATA should not be empty" if data.respond_to?(:empty?) && data.empty?

  cipher(options[:secret]) do |c|
    c.enc(data.is_a?(Hash) ? pack_hash(data) : data.to_s).gsub(/\n/, '')
  end
end

#key(data = {}) ⇒ Object



22
23
24
25
# File 'lib/tokenifier/encrypt.rb', line 22

def key(data = {})
  delimeter = data[:delimeter] || "##"
  Gibberish::SHA256(pack_hash(data, delimeter))
end

#pack_hash(hsh, delimeter = '#') ⇒ Object

data marshaling differs depending to ruby version so its better to pack hash into string accoring to some rule



6
7
8
9
10
# File 'lib/tokenifier/encrypt.rb', line 6

def pack_hash(hsh, delimeter = '#')
  ks = hsh.keys.sort_by(&:to_s)
  fossil = ks.map{ |k| [k,hsh[k]].join(":") }
  fossil.join(delimeter)
end