Skip to content

Instantly share code, notes, and snippets.

@seancribbs
Created July 23, 2009 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seancribbs/152434 to your computer and use it in GitHub Desktop.
Save seancribbs/152434 to your computer and use it in GitHub Desktop.
require 'digest/md5'
# A little HTTP Digest authentication calculator, based on the C code in RFC2617
class DigestAuthCalc < Struct.new(:algorithm, :username, :realm, :password, :nonce,
:cnonce, :nc, :qop, :method, :uri, :entity)
# Calculates the "response" header parameter from the data in the struct
def response
hash_sequence(ha1, nonce) do |resp|
resp << [nc, cnonce, qop] if qop
resp << hash_sequence(method, uri) do |ha2|
ha2 << entity_hash if qop && qop =~ /^auth-int/i
end
end
end
private
def entity_hash
md5hash(entity)
end
def ha1
_ha1 = md5hash(username, realm, password)
if algorithm =~ /^md5-sess/i
md5hash(_ha1, nonce, cnonce)
else
_ha1
end
end
def hash_sequence(*args)
yield args
md5hash(args)
end
def md5hash(*args)
Digest::MD5.hexdigest(args.flatten.compact.join(":"))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment