Module: Hawk::Crypto

Extended by:
Crypto
Included in:
Crypto
Defined in:
lib/hawk/crypto.rb

Instance Method Summary collapse

Instance Method Details

#bewit(options) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/hawk/crypto.rb', line 84

def bewit(options)
  options[:ts] ||= Time.now.to_i + options[:ttl].to_i

  _mac = mac(options.merge(:type => 'bewit'))

  parts = []

  parts << options[:credentials][:id]
  parts << options[:ts]
  parts << _mac
  parts << options[:ext]

  Base64.urlsafe_encode64(parts.join("\\")).chomp.sub(/=+\Z/, '')
end

#hash(options) ⇒ Object



25
26
27
28
29
30
31
32
33
34
# File 'lib/hawk/crypto.rb', line 25

def hash(options)
  parts = []

  parts << "hawk.1.payload"
  parts << options[:content_type]
  parts << options[:payload].to_s
  parts << nil # trailing newline

  Base64.encode64(OpenSSL::Digest.const_get(options[:credentials][:algorithm].upcase).digest(parts.join("\n"))).chomp
end

#mac(options) ⇒ Object



64
65
66
67
68
69
70
71
72
# File 'lib/hawk/crypto.rb', line 64

def mac(options)
  Base64.encode64(
    OpenSSL::HMAC.digest(
      openssl_digest(options[:credentials][:algorithm]).new,
      options[:credentials][:key],
      normalized_string(options)
    )
  ).chomp
end

#normalized_string(options) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/hawk/crypto.rb', line 36

def normalized_string(options)
  options = options.dup
  if !options[:hash] && options.has_key?(:payload) && !options[:payload].nil?
    options[:hash] = hash(options)
  end

  parts = []

  parts << "hawk.1.#{options[:type] || 'header'}"
  parts << options[:ts]
  parts << options[:nonce]
  parts << options[:method].to_s.upcase
  parts << options[:request_uri]
  parts << options[:host]
  parts << options[:port]
  parts << options[:hash]
  parts << options[:ext]

  if options[:app]
    parts << options[:app]
    parts << options[:dig]
  end

  parts << nil # trailing newline

  parts.join("\n")
end

#openssl_digest(algorithm) ⇒ Object



99
100
101
# File 'lib/hawk/crypto.rb', line 99

def openssl_digest(algorithm)
  OpenSSL::Digest.const_get(algorithm.upcase)
end

#ts_mac(options) ⇒ Object



74
75
76
77
78
79
80
81
82
# File 'lib/hawk/crypto.rb', line 74

def ts_mac(options)
  Base64.encode64(
    OpenSSL::HMAC.digest(
      openssl_digest(options[:credentials][:algorithm]).new,
      options[:credentials][:key],
      "hawk.1.ts\n#{options[:ts]}\n"
    )
  ).chomp
end