-
-
Save jeffersonchaves/49797fe2b7f49585c7fcf0b24653572a to your computer and use it in GitHub Desktop.
RSA
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): | |
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 | |
def decripty(d, n, cripty_message): | |
dec_message = [] | |
message = "" | |
for i in cripty_message: | |
dec_message.append(chr(pow(i, d, n))) | |
return message.join(dec_message) | |
message = input() | |
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