凯撒密码python编程加密(python凯撒密码加密解密)

2023-02-14 15:39:20 密语知识 思思

jmu-python-凯撒密码加密算法,谢谢

def encryption():

str_raw = input("请输入明文:")

k = int(input("请输入位移值:"))

str_change = str_raw.lower()

str_list = list(str_change)

str_list_encry = str_list

i = 0

while i len(str_list):

if ord(str_list[i]) 123-k:

str_list_encry[i] = chr(ord(str_list[i]) + k)

else:

print ("解密结果为:"+"".join(str_list_decry))

while True:

print (u"1. 加密")

print(u"2. 解密")

choice = input("请选择:")

if choice == "1": encryption()

elif choice == "2": decryption()

else: print (u"您的输入有误!")

如何用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语言从文件夹中提取文件进行凯撒加密?

import string

def kaisa(s, k): #定义函数 接受一个字符串s 和 一个偏移量k

lower = string.ascii_lowercase #小写字母

upper = string.ascii_uppercase #大写字母

before = string.ascii_letters #无偏移的字母顺序 小写+大写

after = lower[k:] + lower[:k] + upper[k:] + upper[:k] #偏移后的字母顺序 还是小写+大写

#分别把小写字母和大写字母偏移后再加到一起

table = ''.maketrans(before, after) #创建映射表

return s.translate(table) #对s进行偏移 即加密

s = input('请输入一个字符串:')

k = int(input('请输入一个整数密钥:'))

print(kaisa(s, k))

调用此函数

凯撒密码python编程加密(python凯撒密码加密解密) 第1张