Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Large Exponents in Ruby?

I'm just doing some University related Diffie Hellmann exercises and tried to use ruby for it. Sadly, ruby doesn't seem to be able to deal with large exponents:

warning: in a**b, b may be too big
NaN
[...]

Is there any way arround it? (e.g. a special math class or something along that line?)

p.s. here is the code in question:

generator = 7789
prime = 1017473
alice_secret = 415492
bob_secret = 725193

puts from_alice_to_bob = (generator**alice_secret) % prime
puts from_bob_to_alice = (generator**bob_secret) % prime

puts bobs_key_calculation = (from_alice_to_bob**bob_secret) % prime
puts alices_key_calculation = (from_bob_to_alice**alice_secret) % prime
like image 669
Marc Seeger Avatar asked Nov 18 '09 20:11

Marc Seeger


2 Answers

You need to do what is called, modular exponentiation.

like image 67
nlucaroni Avatar answered Sep 29 '22 10:09

nlucaroni


If you can use the OpenSSL bindings then you can do rapid modular exponentiation in Ruby

puts some_large_int.to_bn.mod_exp(exp,mod)
like image 40
Paul Kehrer Avatar answered Sep 29 '22 09:09

Paul Kehrer