Skip to content

Instantly share code, notes, and snippets.

@soul0592
Created July 2, 2013 06:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soul0592/5907113 to your computer and use it in GitHub Desktop.
Save soul0592/5907113 to your computer and use it in GitHub Desktop.
Protocolo Diffie-Hellman
from sys import argv
from random import randint
def primo(num):
for i in range(2,num):
if num % i == 0:
print num,' no es primo'
return 0
else:
print num,' es primo'
return 1
def potmod(x,pot,mod):
bits = pot
res = 1
temp = x
while bits > 0:
if bits%2 == 1:
res = (res * temp) % mod
temp = (temp * temp) % mod
bits = bits >> 1
return res
def bruteForce(generador, primo, F):
for i in range(primo):
valor = potmod(generador, i, primo)
if valor == F:
return i
def main():
g = int(argv[1]) #Base
p = int(argv[2]) #Potencia
#while primo(p) == 0: #La potencia tiene que ser primo
# p = randint(1,50) #Si no es primo se genera un numero nuevo
#a = randint(1,50) #Numero entero escogido por Alice
#b = randint(1,50) #Numero entero escogido por Bob
a = 22
b = 39
A = potmod(g,a,p) #Alice resuelve la funcion de a
print "Alice:\nx = %d\n%d ^ %d mod %d = %d" %(a,g,a,p,A)
B = potmod(g,b,p) #Bob resuelve la funcion de b
print "\nBob:\nx = %d\n%d ^ %d mod %d = %d" %(b,g,b,p,B)
ka = potmod(B,a,p) #Alice obtiene la llave secreta de la funcion de Bob
kb = potmod(A,b,p) #Bob obtiene la llave secreta de la funcion de Alice
if ka == kb:
print "Llave secreta de Alice y Bob: %d" %ka
else:
print "Llaves secretas diferentes."
Ea = bruteForce(g,p,A) #Eve busca el numero secreto de Alice, a
Eb = bruteForce(g,p,B) #Eve busca el numero secreto de Bob, b
ke = potmod(g,Ea*Eb,p) #Eve busca la llave secreta, k
print "\nEve:\nka = %d\nkb = %d\n(%d ^ (%d * %d)) mod % d = %d" %(Ea,Eb,g,Ea,Eb,p,ke)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment