Fixed dumb stuff

master
E. Almqvist 3 years ago
parent 5f57fd5068
commit a73b9dba55
  1. 0
      ma5/rsa/brute.rb
  2. 37
      ma5/rsa/rsa.rb
  3. 34
      ma5/rsa/test.rb

@ -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

@ -1,14 +1,37 @@
#!/usr/bin/ruby -w
require_relative "rsa"
Primes = File.read("primes.txt").chomp.split(",").map do |pstr|
Primes = File.read("smallprimes.txt").chomp.split(",").map do |pstr|
p = pstr.to_i
end
puts "Fetching random primes..."
p1, p2 = Primes.sample, Primes.sample
p1, p2 = 11, 13
def get_random_primes
puts "Fetching random primes..."
p1, p2 = Primes.sample, Primes.sample
return p1, p2
end
def choose_primes
print "1st prime: "
p1 = gets.chomp.to_i
print "2nd prime: "
p2 = gets.chomp.to_i
return p1, p2
end
puts "[1] Random primes"
puts "[2] Choose primes"
ch = gets.chomp.to_i
case ch
when 1
p1, p2 = get_random_primes
when 2
p1, p2 = choose_primes
else
p1, p2 = get_random_primes
end
puts "p1=#{p1}, p2=#{p2}"
puts
@ -23,5 +46,4 @@ puts "Encrypted bytes: #{data.raw}"
data.decrypt!(key.privkey)
puts "Decrypted bytes: #{data.raw}"
p data.data

Loading…
Cancel
Save