Last active
April 28, 2020 02:45
-
-
Save bergpb/b8a834ade2e37bc740e6e8f1300999fb to your computer and use it in GitHub Desktop.
Cifra de Vernan em Python, entrada de texto pelo usuário.
This file contains hidden or 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 | |
| text = input('Entre com o texto a ser cifrado (ou aperte enter para texto padrão):') | |
| if text == '': | |
| text = "O rato roeu a roupa do rei de roma" | |
| def xor(x: str, y: str) -> str: | |
| "Aplica o xor e retorna o binario resultante" | |
| return '{0:b}'.format(int(x, 2) ^ int(y, 2)) | |
| def format_output(msg: list) -> str: | |
| "Formata as saídas" | |
| return ''.join(str(i) for i in msg) | |
| def generate_random_keys(text: str) -> str: | |
| "Gera um conjunto de caracteres com tamanho idêntico para cada item na lista" | |
| item = '' | |
| key = [] | |
| for i in range(len(text)): | |
| for i in range(0, 7): | |
| item += str(random.choice([0, 1])) | |
| key.append(item) | |
| item = '' | |
| return key | |
| def text_into_bin(text: str) -> str: | |
| "Converte texto para string, considerando letra por letra" | |
| binary_text = [format(ord(i), 'b') for i in text] | |
| print("Texto em binário: {}\n".format(format_output(binary_text))) | |
| return binary_text | |
| def generate_key_to_encrypt(text: str) -> str: | |
| "Gera chave com mesmo tamanho do texto criptografado" | |
| key = generate_random_keys(text) | |
| print("Chave gerada: {}\n".format(format_output(key))) | |
| return key | |
| def sending(msg: list, pad: list) -> list: | |
| "Envio de mensagem, onde e aplicado o xor em msg e pad, gerando a cifra" | |
| cipher = [xor(msg[i], pad[i]) for i in range(len(msg))] | |
| print("Cifra gerada: {}\n".format(format_output(cipher))) | |
| return cipher | |
| def receiver(cipher: list, pad: list) -> list: | |
| '''Recebimento de mensagem, onde e aplicado o xor em cifra e pad | |
| gerando a mensagem original''' | |
| origin_msg = [xor(cipher[i], pad[i]) for i in range(len(cipher))] | |
| print("Mensagem original em binário: {}\n".format(format_output(origin_msg))) | |
| msg = [chr(int(item, 2)) for _, item in enumerate(origin_msg)] | |
| print(format_output(msg)) | |
| return origin_msg | |
| msg = text_into_bin(text) | |
| pad = generate_key_to_encrypt(msg) | |
| cipher = sending(msg, pad) | |
| receiver(cipher, pad) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment