Class: Hawk::Crypto::Bewit

Inherits:
Base
  • Object
show all
Defined in:
lib/hawk/crypto.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#eql?

Constructor Details

#initialize(id, key, options, algorithm = 'sha256') ⇒ Bewit

Returns a new instance of Bewit.



151
152
153
154
155
156
# File 'lib/hawk/crypto.rb', line 151

def initialize(id, key, options, algorithm = 'sha256')
  @ts = options[:ts] ||= Time.now.to_i + options[:ttl].to_i
  @ext = options[:ext]
  @id, @key, @options, @algorithm = id, key, options.dup, algorithm
  @mac = options.delete(:mac) if options[:mac]
end

Instance Attribute Details

#extObject (readonly)

Returns the value of attribute ext.



150
151
152
# File 'lib/hawk/crypto.rb', line 150

def ext
  @ext
end

#idObject (readonly)

Returns the value of attribute id.



150
151
152
# File 'lib/hawk/crypto.rb', line 150

def id
  @id
end

#tsObject (readonly)

Returns the value of attribute ts.



150
151
152
# File 'lib/hawk/crypto.rb', line 150

def ts
  @ts
end

Class Method Details

.decode(bewit) ⇒ Object



143
144
145
146
147
148
# File 'lib/hawk/crypto.rb', line 143

def self.decode(bewit)
  padding = '=' * ((4 - bewit.size) % 4)
  id, timestamp, mac, ext = Base64.decode64(bewit + padding).split('\\')

  new(id, nil, { :mac => mac, :ext => ext, :ts => timestamp }, nil)
end

Instance Method Details

#==(other) ⇒ Object



183
184
185
186
187
188
189
190
# File 'lib/hawk/crypto.rb', line 183

def ==(other)
  if self.class === other
    mac == other.mac
  else
    # assume base64 encoded bewit
    self == self.class.decode(other)
  end
end

#encode64Object



175
176
177
# File 'lib/hawk/crypto.rb', line 175

def encode64
  @encoded ||= Base64.urlsafe_encode64(normalized_string).chomp.sub(/=+\Z/, '')
end

#macObject



158
159
160
# File 'lib/hawk/crypto.rb', line 158

def mac
  @mac ||= Crypto::Mac.new(@key, @options.merge(:type => 'bewit'), @algorithm)
end

#normalized_stringObject



162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/hawk/crypto.rb', line 162

def normalized_string
  @normalized_string ||= begin
    parts = []

    parts << @id
    parts << @ts
    parts << mac.to_s
    parts << @ext

    parts.join("\\")
  end
end

#to_s(options = {}) ⇒ Object



179
180
181
# File 'lib/hawk/crypto.rb', line 179

def to_s(options = {})
  encode64
end