python凯撒密码函数 python解凯撒密码

如何用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凯撒密码实现# 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语言从文件夹中提取文件进行凯撒加密?import string
def kaisa(s, k): #定义函数 接受一个字符串s 和 一个偏移量k
lower = string.ascii_lowercase #小写字母
upper = string.ascii_uppercase #大写字母
before = string.ascii_letters #无偏移python凯撒密码函数的字母顺序 小写+大写
after = lower[k:] + lower[:k] + upper[k:] + upper[:k] #偏移后python凯撒密码函数的字母顺序 还是小写+大写
#分别把小写字母和大写字母偏移后再加到一起
table = ''.maketrans(before, after)#创建映射表
return s.translate(table) #对s进行偏移 即加密
s = input('请输入一个字符串python凯撒密码函数:')
k = int(input('请输入一个整数密钥python凯撒密码函数:'))
print(kaisa(s, k))
调用此函数
凯撒密码实现英文短句的加解密1.将“We are students.”这个英文词句用k=4的凯萨密码翻译成密码
1. 恺撒密码,
作为一种最为古老的对称加密体制,他的基本思想是:
通过把字母移动一定的位数来实现加密和解密 。
例如 , 如果密匙是把明文字母的位数向后移动三位,那么明文字母B就变成了密文的E,依次类推,X将变成A,Y变成B,Z变成C,由此可见,位数就是凯撒密码加密和解密的密钥 。
如:ZHDUHVWXGHQWV(后移三位)
2. 凯撒密码,
是计算机C语言编程实现加密和解密 。挺复杂的 。你可以研究一下哦 。
2.将凯撒密码(K=7)的加密、解密过程用C语言编程实现
/*
声明:MSVC++6.0环境测试通过
*/
#includestdio.h
#includectype.h
#define maxlen 100
#define K 7
char *KaisaEncode(char *str)//加密
{
char *d0;
d0=str;
for(;*str!='\0';str++)
{
if(isupper(*str))
*str=(*str-'A'+K)%26+'A';
else if(islower(*str))
*str=(*str-'a'+K)%26+'a';
else
continue;
}
return d0;
}
char *KaisaDecode(char *str)//解密
{
char *d0;
d0=str;
for(;*str!='\0';str++)
{
if(isupper(*str))
*str=(*str-'A'-K+26)%26+'A';
else if(islower(*str))
*str=(*str-'a'-K+26)%26+'a';
else

推荐阅读