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



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

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

Returns:

  • (Boolean)

Raises:

  • (ArgumentError)


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

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



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

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



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

def last_time
  current_time - (30 * 60)
end

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

Returns:

  • (Boolean)

Raises:

  • (ArgumentError)


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

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



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

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



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

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