Module: Hashit::Digests

Included in:
Hashit
Defined in:
lib/hashit/digests.rb

Constant Summary collapse

HASHING_DIGESTS =
%w[md2 md4 md5 sha sha1 sha224 sha256 sha384 sha512]

Instance Method Summary collapse

Instance Method Details

#current_timeObject



25
26
27
28
29
# File 'lib/hashit/digests.rb', line 25

def current_time
  d = DateTime.now
  ts = d.strftime("%s").to_i
  ts - ((d.minute % 30) * 60) - d.second
end

#did_match?(hash, key, text) ⇒ Boolean

Raises:

  • (ArgumentError)


78
79
80
81
82
83
84
# File 'lib/hashit/digests.rb', line 78

def did_match? hash, key, text
  type = get_hash_type hash.split('|').first
  fn = type.to_s.sub("timed", "previous").to_sym
  raise ArgumentError, "invalid hash" if type.nil? || !Hashit.respond_to?(fn)
  new_hash = Hashit.send fn, key, text
  new_hash == hash
end

#generate_hash(digest, key, text) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/hashit/digests.rb', line 35

def generate_hash digest, key, text
  text = prepare text

  if key.is_a? Array
    key.reduce(text) do |text, k|
      k = prepare k
      OpenSSL::HMAC.hexdigest(digest, k, text)
    end
  else
    key = Hashit.prepare key
    OpenSSL::HMAC.hexdigest(digest, key, text)
  end
end

#last_timeObject



31
32
33
# File 'lib/hashit/digests.rb', line 31

def last_time
  current_time - (30 * 60)
end

#matches?(hash, key, text) ⇒ Boolean

Raises:

  • (ArgumentError)


71
72
73
74
75
76
# File 'lib/hashit/digests.rb', line 71

def matches? hash, key, text
  type = get_hash_type hash.split('|').first
  raise ArgumentError, "invalid hash" if type.nil? || !Hashit.respond_to?(type)
  new_hash = Hashit.send type, key, text
  new_hash == hash
end

#prepare(obj) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/hashit/digests.rb', line 49

def prepare obj
  return obj if obj.is_a? String

  if obj.is_a? Array
    obj = prepare_array obj
  elsif obj.nil?
    raise ArgumentError, "Nil passed in as a text parameter"
  elsif obj.respond_to? :to_s
      obj = obj.to_s
  else
    raise ArgumentError, "Parameter #{obj} cannot be converted to string"
  end

  obj
end

#prepare_array(arr) ⇒ Object



65
66
67
68
69
# File 'lib/hashit/digests.rb', line 65

def prepare_array arr
  arr.reduce("") do |str, el|
    str += prepare el
  end
end