怎么用Python编辑出此凯撒密码的解密密码 (python编程题凯撒密码)

2023-03-19 4:51:05 密码用途 思思

凯撒密码的加密密钥与解密密钥是相反数,因此,k给相反数即可:

kaisa(kaisa(s, 3), -3)

python凯撒密码实现

# codinng=utf-8

x = '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'.split(' ')

y = 'n o p q r s t u v w x y z a b c d e f g h i j k l m'.split(' ')

X = map(lambda x: x.upper(), x)

Y = map(lambda x: x.upper(), y)

dict_kaisa = dict(zip(x + X, y + Y))  # 创建一个字典, 键为原字符串, 值为加密字符串

# 定义凯撒加密函数, 输入字符串, 输出凯撒加密后字符串

def kaisa(string):

    result = []

    for i in range(len(string)):

        if string[i] in dict_kaisa.keys():

            result.append(dict_kaisa[string[i]])

        else:

            result.append(string[i])

    return ''.join(result)

print(kaisa('The Zen of Python'))  # 结果为Gur Mra bs Clguba

如何用python编写凯撒密码 ?

凯撒密码是对字母表整体进行偏移的一种变换加密。因此,建立一个字母表,对明文中每个字母,在这个字母表中偏移固定的长度即可得到对应的密文字母。

最基本的实现如下:

def caesarcipher(s: str,rot: int=3) -str:

    _ = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

    encode = ''

    i = 0

    for c in s:

        try:

            encode += _[(_.index(c.upper()) + rot) % len(_)]

        except (Exception,) as e:

            encode += c

    return encode

print(caesarcipher('hellow'))

print(caesarcipher('KHOORZ', -3))

如果要求解密后保持大小写,那么,字母表_还需要包含所有小写字母并且index时不对c做upper处理.

同样的,也可以在字母表中追加数字,各种符号,空格等.

Python编程-翻译密码?

区分大小写的凯撒密码。

在凯撒密码的基础上针对大写与小字字符区分处理即可:

解密只需要将7换成19(因为26-7=19),或者使用-7也可以:

print(caesarcipher(caesarcipher('Student!', 7),19))