From b889ef34d4fff0d156901ae2aebfcee02339ce77 Mon Sep 17 00:00:00 2001 From: Azul Date: Thu, 4 Oct 2012 10:22:46 +0200 Subject: some cleanup, sha functions now concat multiple args also u does not depend on n --- lib/srp/authentication.rb | 2 +- lib/srp/client.rb | 4 ++-- lib/srp/util.rb | 29 +++++++++++++++-------------- 3 files changed, 18 insertions(+), 17 deletions(-) diff --git a/lib/srp/authentication.rb b/lib/srp/authentication.rb index 0505a58..0fd275c 100644 --- a/lib/srp/authentication.rb +++ b/lib/srp/authentication.rb @@ -17,7 +17,7 @@ module SRP end def u - calculate_u(aa, bb, BIG_PRIME_N) + calculate_u(aa, bb) end # do not cache this - it's secret and someone might store the diff --git a/lib/srp/client.rb b/lib/srp/client.rb index 947bd7b..65052f5 100644 --- a/lib/srp/client.rb +++ b/lib/srp/client.rb @@ -20,7 +20,7 @@ module SRP a = bigrand(32).hex aa = modpow(GENERATOR, a, BIG_PRIME_N) # A = g^a (mod N) bb = server.handshake(username, aa) - u = calculate_u(aa, bb, BIG_PRIME_N) + u = calculate_u(aa, bb) client_s = calculate_client_s(x, a, bb, u) server.validate(calculate_m(aa, bb, client_s)) end @@ -35,7 +35,7 @@ module SRP def calculate_x(username = @username, password = @password) shex = '%x' % [@salt] inner = sha256_str([username, password].join(':')) - sha256_str([shex].pack('H*') + [inner].pack('H*')).hex + sha256_hex(shex, inner).hex end def calculate_client_s(x, a, bb, u) diff --git a/lib/srp/util.rb b/lib/srp/util.rb index cafa5f4..fcbab31 100644 --- a/lib/srp/util.rb +++ b/lib/srp/util.rb @@ -30,8 +30,15 @@ d15dc7d7b46154d6b6ce8ef4ad69b15d4982559b297bcf1885c529f566660e5 end end - def sha256_hex(h) - Digest::SHA2.hexdigest([h].pack('H*')) + # Hashes the (long) int args + def sha256_int(*args) + sha256_hex(*args.map{|a| a.to_s(16)}) + end + + # Hashes the hex args + def sha256_hex(*args) + h = args.join('') + sha256_str([h].pack('H*')) end def sha256_str(s) @@ -49,23 +56,17 @@ d15dc7d7b46154d6b6ce8ef4ad69b15d4982559b297bcf1885c529f566660e5 protected def calculate_multiplier - n = BIG_PRIME_N - g = GENERATOR - nhex = '%x' % n - ghex = '0%x' % g - hashin = [nhex].pack('H*') + [ghex].pack('H*') - sha256_str(hashin).hex + # GENERATOR hex needs to be prefixed with 0 so it's not "2" -> 32 + ghex = '0%x' % GENERATOR + sha256_hex(BIG_PRIME_N.to_s(16), ghex).hex end def calculate_m(aa, bb, s) - hashin = '%x%x%x' % [aa, bb, s] - sha256_hex(hashin).hex + sha256_int(aa, bb, s).hex end - def calculate_u(aa, bb, n) - aahex = '%x' % [aa] - bbhex = '%x' % [bb] - return sha256_hex("%x%x" % [aa, bb]).hex + def calculate_u(aa, bb) + sha256_int(aa, bb).hex end end -- cgit v1.2.3