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.



153
154
155
156
157
158
# File 'lib/hawk/crypto.rb', line 153

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.



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

def ext
  @ext
end

#idObject (readonly)

Returns the value of attribute id.



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

def id
  @id
end

#tsObject (readonly)

Returns the value of attribute ts.



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

def ts
  @ts
end

Class Method Details

.decode(bewit) ⇒ Object



145
146
147
148
149
150
# File 'lib/hawk/crypto.rb', line 145

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



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

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

#encode64Object



177
178
179
# File 'lib/hawk/crypto.rb', line 177

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

#macObject



160
161
162
# File 'lib/hawk/crypto.rb', line 160

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

#normalized_stringObject



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

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



181
182
183
# File 'lib/hawk/crypto.rb', line 181

def to_s(options = {})
  encode64
end