如何编写Ceaser密码Python [英] How to write a Ceaser Cipher Python

查看:52
本文介绍了如何编写Ceaser密码Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定如何开始编写程序.

I am not sure how to start writing the program.

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()

很抱歉,我不确定如何开始.另外,请提供建议而不是答案.

Sorry for the question I am not sure how to begin. Also please give advice not the answer.

推荐答案

在数学上,如果我们在 Caesar cipher 中看到 encryption 技术,则获得加密字母的公式为:

Mathematically, if we see encryption technique in Caesar cipher, then the formula to get encrypted letter is:

c = (x+n) mod 26, 

其中 c 是加密字母的位置值, x 是实际字母的位置值,而 n 是移位.同样,要解密每个字母,我们使用下面给出的公式:

where c is place value of encrypted letter, x is place value of actual letter and n is the shift. Similarly, to decrypt each letter, we use the formula given below:

c = (x-n) mod 26

您可以使用下面的代码来了解如何实现 Caesar Cipher :

You can use my below code to get an idea of how to implement 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

这篇关于如何编写Ceaser密码Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆