import socket
from rsa_operations import *
from random import randint
from sys import argv
import time
port = int(argv[1])
def search_public_key(host):
f = open("users.dat", "r")
for line in f.readlines():
name, e, n = line.split(" ")
if host == name:
return int(e), int(n)
return -1, -1
rsa_math = RSAMath()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", port))
s.listen(3)
sc, sddr = s.accept()
m = randint(5, 20)
e, n = 0, 0
rec = sc.recv(1024)
#print rec
if "connected" in rec:
hostname, tmp = rec.split(" ")
r = randint(1, 100)
my_y = rsa_math.function(r)
sc.send("r")
time.sleep(0.2)
sc.send(str(r))
#print "Random %s"%r
print "RSA Server"
while True:
rec = sc.recv(1024)
#print rec
if "says:" in rec:
print rec
if rec == "c":
c = int(sc.recv(1024))
e, n = search_public_key(hostname)
if e == -1 and n == -1:
print "Public Key not found.Finishing..."
sc.close()
s.close()
else:
client_y = rsa_math.exp(c, e) % n
#print client_y, my_y
if client_y == my_y:
print "Welcome to the RSA Server %s"%hostname
sc.send("ok")
else:
print "Authentication Error. Finishing..."
sc.close()
s.close()
sc.close()
s.close()