Как написать Ceaser Cipher Python - PullRequest
0 голосов
/ 08 июля 2019

Я не уверен, как начать писать программу.

input = input("Input the text you would like encrypted")


def cipher_text(letter_code):
    for i in input:
        number_code = ord(i) + 3
        letter_code = chr(number_code)
        print(letter_code)

def plain_text(letter_code,regular_text):
    for i in input:
        regular_text = letter_code - 3
        print(regular_text)
print("Encrypted text")
cipher_text()
print("Unencrypted text")
plain_text()

Извините за вопрос, я не уверен, как начать. Также, пожалуйста, дайте совет, а не ответ.

1 Ответ

0 голосов
/ 08 июля 2019

Математически, если мы видим encryption технику в Caesar cipher, то формула для получения зашифрованного письма:

c = (x+n) mod 26, 

, где c - это значение места зашифрованной буквы, x - это значение места фактической буквы, а n - это смещение. Аналогично, для decrypt каждой буквы мы используем формулу, приведенную ниже:

c = (x-n) mod 26

Вы можете использовать мой код ниже, чтобы получить представление о том, как реализовать Caesar Cipher:

def encrypt(plain_text, s):
    encrypted_text = ''
    for i in range(len(plain_text)):
        if plain_text[i] == ' ':
            encrypted_text = encrypted_text + plain_text[i]
        elif plain_text[i].isupper():
            encrypted_text = encrypted_text + chr((ord(plain_text[i])+s-65)%26+65)
        else:
            encrypted_text = encrypted_text + chr((ord(plain_text[i])+s-97)%26+97)
    return encrypted_text


def decrypt(encrypt_text, s):
    decrypted_text = ''
    for i in range(len(encrypt_text)):
        if encrypt_text[i] == ' ':
            decrypted_text = decrypted_text + encrypt_text[i]
        elif encrypt_text[i].isupper():
            decrypted_text = decrypted_text + chr((ord(encrypt_text[i])-s-65)%26+65)
        else:
            decrypted_text = decrypted_text + chr((ord(encrypt_text[i])-s-97)%26+97)
    return decrypted_text



plain_text = input("Input the text you would like encrypted:")
s = int(input("Enter shift:"))
encrypt_text = encrypt(plain_text, s)
print("Encrypted text: {}".format(encrypt_text))
print("Decrypted text: {}".format(decrypt(encrypt_text, s)))

Пример вывода:

Input the text you would like encrypted:Taj Mahal

Enter shift:3
Encrypted text: Wdm Pdkdo
Decrypted text: Taj Mahal
...