2020-11-25 13:31:48 +01:00
|
|
|
#!/usr/bin/ruby
|
|
|
|
|
|
|
|
#####################################
|
|
|
|
#
|
|
|
|
# Marcin Woźniak
|
|
|
|
# s434812
|
|
|
|
#
|
|
|
|
#####################################
|
|
|
|
|
|
|
|
require 'socket'
|
|
|
|
|
|
|
|
load 'modul1.rb'
|
|
|
|
|
|
|
|
sock = TCPSocket.new("localhost",3000)
|
|
|
|
puts sock.gets
|
|
|
|
|
2020-11-29 14:16:08 +01:00
|
|
|
|
|
|
|
starting = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
|
|
|
2020-11-25 13:31:48 +01:00
|
|
|
# Generate public and priv key
|
2020-11-26 17:15:34 +01:00
|
|
|
def generateKeys
|
2020-11-29 14:16:08 +01:00
|
|
|
p = 0
|
|
|
|
q = 0
|
|
|
|
|
|
|
|
pThread = Thread.new {
|
|
|
|
while true
|
2020-12-01 15:28:18 +01:00
|
|
|
p = generate(4072)
|
2020-11-29 14:16:08 +01:00
|
|
|
if primalityTest(p)
|
|
|
|
break
|
|
|
|
end
|
|
|
|
end
|
|
|
|
}
|
|
|
|
|
|
|
|
qThread = Thread.new {
|
2020-11-26 17:15:34 +01:00
|
|
|
while true
|
2020-12-01 15:28:18 +01:00
|
|
|
q = generate(4072)
|
2020-11-29 14:16:08 +01:00
|
|
|
if primalityTest(q)
|
|
|
|
break
|
|
|
|
end
|
|
|
|
end
|
|
|
|
}
|
2020-11-26 17:15:34 +01:00
|
|
|
|
2020-11-29 14:16:08 +01:00
|
|
|
pThread.join
|
|
|
|
qThread.join
|
2020-11-25 13:31:48 +01:00
|
|
|
|
2020-11-29 14:16:08 +01:00
|
|
|
n = p * q
|
|
|
|
phi = (p-1)*(q-1)
|
2020-11-25 13:31:48 +01:00
|
|
|
|
2020-11-29 14:16:08 +01:00
|
|
|
while true
|
|
|
|
e = SecureRandom.random_number(0..phi)
|
2020-11-26 17:15:34 +01:00
|
|
|
d = reciprocal_Phi_p(e,phi)
|
2020-11-29 14:16:08 +01:00
|
|
|
if nwd(e,phi) == 1 && d > 1
|
|
|
|
return [n,e,d]
|
2020-11-26 17:15:34 +01:00
|
|
|
end
|
2020-11-25 13:31:48 +01:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2020-11-26 17:15:34 +01:00
|
|
|
keys = generateKeys
|
|
|
|
n = keys[0]
|
|
|
|
e = keys[1]
|
|
|
|
d = keys[2]
|
2020-11-29 14:16:08 +01:00
|
|
|
puts "d: " + d.inspect
|
2020-11-25 13:31:48 +01:00
|
|
|
|
|
|
|
pubKey = [n,e]
|
|
|
|
privKey = [n,d]
|
|
|
|
|
|
|
|
puts
|
|
|
|
puts "privKey " + privKey.inspect
|
|
|
|
puts "pubKey " + pubKey.inspect
|
|
|
|
puts
|
|
|
|
|
|
|
|
# Sending pubKey
|
|
|
|
sock.puts pubKey[0]
|
|
|
|
sock.puts pubKey[1]
|
|
|
|
|
|
|
|
# Getting cipher
|
|
|
|
cipher = sock.gets.gsub(/\n$/, '')
|
|
|
|
message = betterExponentiation(cipher.to_i,d.to_i,n.to_i)
|
|
|
|
|
|
|
|
puts "Cipher: " + cipher.inspect
|
|
|
|
puts "Message: " + message.inspect
|
|
|
|
|
|
|
|
# Close socket
|
|
|
|
sock.close
|
2020-11-29 14:16:08 +01:00
|
|
|
|
|
|
|
ending = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
|
|
elapsed = ending - starting
|
|
|
|
puts "Time " + elapsed.inspect
|