From c09f985b74953a3cce32bddb2de82d3e668e8976 Mon Sep 17 00:00:00 2001 From: tabsoverspaces Date: Wed, 3 Jun 2020 17:44:45 +0200 Subject: [PATCH 1/2] Tests were failing due to Random::Secure.hex receiving float argument. Made cast to Int. --- src/ecdsa/math.cr | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/src/ecdsa/math.cr b/src/ecdsa/math.cr index 4051502..c63bd0b 100644 --- a/src/ecdsa/math.cr +++ b/src/ecdsa/math.cr @@ -18,23 +18,22 @@ module ECDSA end def self.mod_exp(a : BigInt, exp : BigInt, mod : BigInt) - res = BigInt.new(1); + res = BigInt.new(1) while (exp > 0) if ((exp & 1) > 0) - res = (res*a).modulo(mod); + res = (res*a).modulo(mod) end - exp >>= 1; + exp >>= 1 a = (a*a).modulo(mod) end - return res; + return res end - - + def self.mod_sqrt(a : BigInt, n : BigInt) : BigInt # CAUTION: This works ONLY if n is prime but we do not check - We also do not check if a is a quadratic residue # https://en.wikipedia.org/wiki/Quadratic_residue if n % 4 == 3 - return mod_exp(a,(n+1) // 4, n) + return mod_exp(a, (n + 1) // 4, n) end raise Exception.new "Not implemented" end @@ -80,7 +79,7 @@ module ECDSA n1, n2 = n2, n1 if n1 > n2 # number of bits of (n1..n2) - bin_length = (n2-n1).to_s(2).bytesize + bin_length = (n2 - n1).to_s(2).bytesize # puts "bin_length of range: #{bin_length}" # number of bytes required @@ -90,7 +89,7 @@ module ECDSA # puts (n2-n1).to_s(2) # get random bytes, convert to binary and cut down size - s = BigInt.new(Random::Secure.hex(n_bytes), base: 16).to_s(2)[0, bin_length] + s = BigInt.new(Random::Secure.hex(n_bytes.to_i), base: 16).to_s(2)[0, bin_length] # puts s r = n1 + BigInt.new(s, base: 2) r = random(n1, n2) if r > n2 @@ -98,4 +97,4 @@ module ECDSA return r end end -end \ No newline at end of file +end From e10c611240557e1ba30a75dda4c1f2c500b62c95 Mon Sep 17 00:00:00 2001 From: tabsoverspaces Date: Wed, 3 Jun 2020 18:20:54 +0200 Subject: [PATCH 2/2] Removed cast; added floored division. --- src/ecdsa/math.cr | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ecdsa/math.cr b/src/ecdsa/math.cr index c63bd0b..5d12d9e 100644 --- a/src/ecdsa/math.cr +++ b/src/ecdsa/math.cr @@ -83,13 +83,13 @@ module ECDSA # puts "bin_length of range: #{bin_length}" # number of bytes required - n_bytes = bin_length / 8 + n_bytes = bin_length // 8 n_bytes += 1 unless bin_length % 8 == 0 # puts "n_bytes required: #{n_bytes}" # puts (n2-n1).to_s(2) # get random bytes, convert to binary and cut down size - s = BigInt.new(Random::Secure.hex(n_bytes.to_i), base: 16).to_s(2)[0, bin_length] + s = BigInt.new(Random::Secure.hex(n_bytes), base: 16).to_s(2)[0, bin_length] # puts s r = n1 + BigInt.new(s, base: 2) r = random(n1, n2) if r > n2