Loading [MathJax]/extensions/TeX/AMSsymbols.js

jueves, 13 de septiembre de 2012

RSA Authentication

For this week, we had to do the following:
  •  Implement RSA authentication in Python for a client-server system with sockets.

Key generation
RSA involves a public key and a private key. The public key can be known to everyone and is used for encrypting messages. Messages encrypted with the public key can only be decrypted using the private key. 

So, the algorithm is:

    * Generate n = p × q, where both p and q are prime.
    * (e, n) is the public key; c = m^e mod n.
    * e is to be relatively prime with ɸ(n)
    * (d, n) is the private key; m = c^d mod n.
          o Requirement: e × d ≣ 1 mod ɸ(n) (or in other words d needs to be the inverse multiplicative of e);
    * ɸ(n) = (p - 1) × (q - 1).
    * m^(e×d)≣ m mod n due to Euler’s theorem.

 
These are the results.


Code RSAKeys: 


import math
import random
from random import randint
def t_primo(num):
for i in range(2,num):
if num % i == 0:
return False
return True
def mcd(phi_n, e): #obtener el facor comun de phi
if phi_n % e == 0:
return e
else:
return mcd(e, phi_n%e)
def gcde(e,phi_n):
a, A = 0, 1
c, C = 1, 0
while phi_n:
coct = e // phi_n
e, phi_n = phi_n, e%phi_n
a, A = A - coct * a, a
c, C = C - coct * c, c
return(A, C, e)
def inverso(e, phi_n):
a, c, gcd = gcde(e,phi_n)
if gcd == 1:
return (a+phi_n)%phi_n
else:
return 0
def g_primo():
while True:
num = randint(50,100)
if t_primo(num):
break
return num
def crear_e(phi_n):
e = g_primo()
#print e
if(mcd(phi_n, e) == 1):
return e
else:
crear_e(phi_n)
def claves(user1,d,e,n):
a= str(user1)+" "+str(e) +" "+str(n)+"\n"
b= str(user1)+" "+str(d) +" "+str(n)+"\n"
arch=open("Server_keys.txt","a")
arch.write(a)
arch.close
us= str(user1)+ ".txt"
arch2=open(us,"a")
arch2.write(b)
arch2.close
def main():
user1=raw_input("Nombre de usuario:")
#clave=claves(user1,d,e,n)
p = g_primo()
q = g_primo()
print p
print q
n = p*q
print n
phi_n =(p-1)*(q-1)
print phi_n
e = crear_e(phi_n)
print e
d = inverso(e, phi_n)
print d
clave=claves(user1,d,e,n)
print clave
main()
view raw gistfile1.py hosted with ❤ by GitHub




Server:

import socket
import random
import socket,sys,pickle
from math import sqrt
#if __name__ == '__main__':
def bArchivo(usuario):
file = open("Server_keys.txt", "r")
for linea in archivo.readlines():
if len(linea)==0:
continue
lin = linea.split()
if lin[0] == usuario:
dato1=[int(lin[1]), int(lin[2])]
return dato1
else:
linea += 1
return False
file.close()
return False
def fun(x):
x =(x*sqrt(3)+7)
return x
def main():
# Se prepara el servidor
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("", 8000))
server.listen(1)
print "Esperando clientes..."
# bucle para atender clientes
while 1:
# Se espera a un cliente
socket_cliente, datos_cliente = server.accept()
# Se escribe su informacion
print "conectado "+str(datos_cliente)
x=randint(1,1000)
usuario=socket_cliente.recv(1000)
socket_cliente.send(str(x))
seguir = True
while seguir:
# Espera por datos
peticion = socket_cliente.recv(1000)
if dato1 == False:
dato1= bArchivo(peticion)
print "no identificado"
socket_s.close()
client_socket.close()
e = dato1[0]
n = dato1[1]
y = (int(request)**e)%n
# Contestacion a "hola"
if fun (x) == y:
#print str(datos_cliente)+ " envia hola: contesto"
socket_cliente.send("hola")
else:
socket_client.send("fail")
socket_client.close()
main()
view raw gistfile1.py hosted with ❤ by GitHub


Cliente: 
 Here I have a difficult with of server, this is the code but it hasn´function
import socket
from math import sqrt
def bArchivo(usuario):
file = open("Server_keys.txt", "r")
for linea in archivo.readlines():
if len(linea)==0:
continue
lin = linea.split()
if lin[0] == usuario:
dato1=[int(lin[1]), int(lin[2])]
return dato1
else:
linea += 1
#return False
file.close()
return False
def fun(x):
x =(x*sqrt(3)+7)
return x
def main():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("", 8000))
server.listen(1)
print " clientes..."
socket_cliente, datos_cliente = server.accept()
# Se escribe su informacion
print "conectado cliente "+str(datos_cliente)
#x=randint(1,1000)
socket_cliente.send(str(x)) peticion = socket_cliente.recv(1000)
print Client
rx = int(x)
y = funcion(rx)
usuario = raw_input("usuario:")
dato1= bArchivo(request)
if dato1 == False
print no eres
d=dato1[0]
n=dato1[1]
r =str(pow(y,d) %n)
#print str(datos_cliente)+ " envia adios: contesto y desconecto"
socket_cliente.send(usuario)
socket_cliente.send(r)
socket_cliente.close()
main()
view raw gistfile1.py hosted with ❤ by GitHub

1 comentario:

  1. No elevar a exponentes directo (es indificiente) y además en "y = (int(request)**e)%n" no parece estar definida la variable request... Lo mismo ocurre en en cliente. La comunicación esperaría que pase con send() y recv() ... Van 4 pts.

    ResponderEliminar