|
|
|
@ -1,13 +1,37 @@ |
|
|
|
|
module RSA |
|
|
|
|
def self.n_inv(a, m) |
|
|
|
|
(1..m).each{|x| break x if (a*x % m == 1)} |
|
|
|
|
def self.egcd(a, b) |
|
|
|
|
if a == 0 then |
|
|
|
|
return b, 0, 1 |
|
|
|
|
else |
|
|
|
|
g, y ,x = self.egcd(b % a, a) |
|
|
|
|
return g, x - (b.to_i / a.to_i)*y, y |
|
|
|
|
end |
|
|
|
|
end |
|
|
|
|
|
|
|
|
|
def self.modinv(a, m) |
|
|
|
|
g, x, y = self.egcd(a, m) |
|
|
|
|
if g != 1 then |
|
|
|
|
raise "Mod inv does not exist" |
|
|
|
|
else |
|
|
|
|
return x % m |
|
|
|
|
end |
|
|
|
|
end |
|
|
|
|
|
|
|
|
|
class Key |
|
|
|
|
private def find_d |
|
|
|
|
puts "Generating private key..." |
|
|
|
|
begin |
|
|
|
|
return @d |
|
|
|
|
rescue RuntimeError |
|
|
|
|
puts "d not found, retrying..." |
|
|
|
|
retry |
|
|
|
|
end |
|
|
|
|
end |
|
|
|
|
|
|
|
|
|
def initialize(p1, p2) |
|
|
|
|
puts "Generating key pair..." |
|
|
|
|
@n = p1 * p2 |
|
|
|
|
@phi = (p1-1)*(p2-1) |
|
|
|
|
@phi = (p1-1).lcm(p2-1) |
|
|
|
|
|
|
|
|
|
enc = [] |
|
|
|
|
(2...@phi).each do |e| |
|
|
|
@ -18,10 +42,9 @@ module RSA |
|
|
|
|
end |
|
|
|
|
end |
|
|
|
|
@e = enc.sample |
|
|
|
|
p enc |
|
|
|
|
@d = RSA.modinv(@e, @phi) |
|
|
|
|
|
|
|
|
|
@d = RSA.n_inv(@e, @n) |
|
|
|
|
puts "e=#{@e} d=#{@d}" |
|
|
|
|
puts "e: #{@e} d: #{@d}" |
|
|
|
|
end |
|
|
|
|
|
|
|
|
|
def pubkey |
|
|
|
@ -42,7 +65,7 @@ module RSA |
|
|
|
|
c.ord.to_i |
|
|
|
|
end |
|
|
|
|
end |
|
|
|
|
puts "Generated bytearray: #{@data}" |
|
|
|
|
puts "Generated bytes: #{self.raw}" |
|
|
|
|
end |
|
|
|
|
|
|
|
|
|
def raw |
|
|
|
|