凯撒密码是对字母表整体进行偏移的一种变换加密。因此,建立一个字母表,对明文中每个字母,在这个字母表中偏移固定的长度即可得到对应的密文字母。
最基本的实现如下:
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处理.
同样的,也可以在字母表中追加数字,各种符号,空格等.
凯撒密码作为一种最为古老的对称加密体制,在古罗马的时候都已经很流行,他的基本思想是:通过把字母移动一定的位数来实现加密和解密。明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。例如,当偏移量是3的时候,所有的字母A将被替换成D,B变成E,以此类推X将变成A,Y变成B,Z变成C。由此可见,位数就是凯撒密码加密和解密的密钥。如下代码是以偏移量为13展开计算的。123
源代码如下:
sr1="abcdefghijklmnopqrstuvwxyz"sr2=sr1.upper()
sr=sr1+sr1+sr2+sr2
st="The Zen of Python"sResult=""for j in st:if j==" ":
sResult = sResult +" "
continue
i=sr.find(j)if(i>-1):
sResult=sResult+sr[i+13]print sResult12345678910111213
运行结果为:
Gur Mra bs Clguba