凯撒加密解密算法(python)
22 Apr 2013无聊的时候折腾一下虾米正版歌曲破解下载,遇到了凯撒加密算法,写一写。
凯撒加密(Caesar cipher)是一种简单的消息编码方式:它根据字母表将消息中的每个字母移动常量位k。举个例子如果k等于3,则在编码后的消息中,每个字母都会向前移动3位:a会被替换为d;b会被替换成e;依此类推。字母表末尾将回卷到字母表开头。于是,w会被替换为z,x会被替换为a。
# Casare Algorithm
def convert(c, key, start = 'a', n = 26):
a = ord(start)
offset = ((ord(c) - a + key)%n)
return chr(a + offset)
def caesarEncode(s, key):
o = ""
for c in s:
if c.islower():
o+= convert(c, key, 'a')
elif c.isupper():
o+= convert(c, key, 'A')
else:
o+= c
return o
def caesarDecode(s, key):
return caesarEncode(s, -key)
if __name__ == '__main__':
key = 3
s = 'This is Casare Algorithm.'
e = caesarEncode(s, key)
d = caesarDecode(e, key)
print e
print d
运行结果:
转载请注明:于哲的博客 » 凯撒加密解密算法(python)
