用恺撒密码对信息进行加密

使用字符串和列表两种方法来解决项目问题;

要求:对加密后的信息反向进行解密,要求不使用.join()方法,改为循环方法输出最终字符串。

参考 https://blog.csdn.net/qq_38902844/article/details/106169852

恺撒密码是古罗马恺撒大帝用来对军事情报进行加解密的算法,它采用了替换方法对信息中的每一个英文字符循环替换为字母表序列中该字符后面的第三个字符,即,字母表的对应关系如下:‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬

原文:A B C D E F G H I J K L M N O P Q R S T U V W X Y Z‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬

密文:D E F G H I J K L M N O P Q R S T U V W X Y Z A B C‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬

对于原文字符P,其密文字符C满足如下条件:C=(P+3) mod 26‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬

上述是凯撒密码的加密方法,解密方法反之,即:P=(C-3) mod 26‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬

假设用户可能使用的输入包含大小写字母、空格和特殊符号,请编写一个程序,对输入字符串进行恺撒密码加密,直接输出结果,其中空格不用进行加密处理。使用input()获得输入。

# 本程序主要用来实现恺撒密码

string = input("请输入原文:")
print("转换后的密文为:")
for i in range(len(string)) :
    if 'a' <= string[i] <= 'z' :
        # chr函数,返回Unicode码对应的字符
        # ord函数,返回字符对应的Unicode码
        print(chr(ord('a') + (ord(string[i])-ord('a')+3) % 26), end="")
    elif 'A' <= string[i] <= 'Z' :
        print(chr(ord('A') + (ord(string[i])-ord('A')+3) % 26), end="")
    else :
        # end="" 可以实现输出不换行的效果
        print(string[i], end="")


用列表方法

string = input("请输入原文:")
li = list(string)
for i in range(len(li)) :
    if 'a' <= li[i] <= 'z' :
        # chr函数,返回Unicode码对应的字符
        # ord函数,返回字符对应的Unicode码
        li[i] = chr(ord('a') + (ord(li[i])-ord('a')+3) % 26)
    elif 'A' <= li[i] <= 'Z' :
        li[i] = chr(ord('A') + (ord(li[i])-ord('A')+3) % 26)
print("转换后的密文为:")
for i in range(len(li)) :
    print(li[i], end="")

参考如下代码:

ori = 'sbwkrq lv dq hafhoohqw odqjxdjh'
for x in ori:
    if ord('a') <= ord(x) <= ord('z'):
        ec = chr((ord(x)-3-ord('a')) % 26+ord('a'))
    elif ord('A') <= ord(x) <= ord('Z'):
        ec = chr((ord(x)-3-ord('A')) % 26+ord('A'))
    else:
        ec = x
    print(ec, end="")
#python is an excellent language