Created
October 3, 2016 17:10
-
-
Save marrcandre/f594c29498a0a0a265a800b7a8c47157 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
def euclides(e, phi): | |
'''documentação da função''' | |
r, r1 = e, phi | |
d, v = 1, 0 | |
u1, v1 = 0, 1 | |
while r1 != 0: | |
q = int(r / r1) # pega apenas a parte inteira | |
rs = r | |
us = d | |
vs = v | |
r = r1 | |
d = u1 | |
v = v1 | |
r1 = rs - q * r1 | |
u1 = us - q * d | |
v1 = vs - q * v1 | |
return r, d, v # tais que a*d + b*v = r et r = pgcd | |
def modular_inverse(e, phi): | |
mdc, d = euclides(e, phi)[:2] | |
assert mdc == 1 | |
if d < 0: | |
d += phi | |
return d | |
# GERACAO DAS CHAVES | |
def generate_keys(): | |
p, q = 3490529510847650949147849619903898133417764638493387843990820577, \ | |
32769132993266709549961988190834461413177642967992942539798288533 | |
# 2 - Compute n = p*q | |
n = p * q | |
# 3 phi totient de n phi(p.q) | |
phi = (p - 1) * (q - 1) | |
# 4 Escolha um inteiro "e" tal que e seja maior que 1 e coprimo de phi | |
e = random.randrange(2, phi) | |
g = euclides(e, phi)[0] | |
# se g é diferente de 1 sorteia outro numero para que sejam coprimos ou seja seu MDC e igual a 1 | |
while g != 1: | |
e = random.randrange(1, phi) | |
g = euclides(e, phi)[0] | |
# 5 | |
d = modular_inverse(e, phi) | |
return (e, n), (d, n) | |
def cripty(e, n, message): | |
# enc_message = [] | |
# | |
# for c in message: | |
# enc_message.append(pow(ord(c), e, n)) | |
# | |
# return enc_message | |
return [pow(ord(c), e, n) for c in message] | |
def decripty(d, n, cripty_message): | |
# dec_message = [] | |
# separator = "" | |
# | |
# for i in cripty_message: | |
# dec_message.append(chr(pow(i, d, n))) | |
return ''.join([chr(pow(i, d, n)) for i in cripty_message]) | |
message = input('Texto aberto: ') | |
keys = generate_keys() | |
print("CHAVES: ") | |
print(keys) | |
print("MENSAGEM ORIGINAL: ") | |
print(message) | |
message_cript = (cripty(keys[0][0], keys[0][1], message)) | |
print("\nCRIPTOGRAFADA") | |
print(message_cript) | |
print("\n\nDESCRIPTOGRAFADA: ") | |
print(decripty(keys[1][0], keys[1][1], message_cript)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment