凯撒密码
class CaesarCipher:
def __init__(self, alphabet, shift):
self.alphabet = alphabet
self.asize = len(alphabet)
self.shift = shift
self._dict = {}
for i, c in enumerate(ALPHABET):
self._dict[c] = i
def _encode(self, c):
return self.alphabet[(self._dict[c]+self.shift)%self.asize]
def encode(self, s):
o = ''
for c in s:
o += self._encode(c)
return o
if __name__ == '__main__':
ALPHABET = 'abcdefghijklmnopqrstuvwxyz'
cipher = CaesarCipher(ALPHABET, 3)
code = cipher.encode('hello')
print(code)
ROT13
即把 凯撒密码 的偏置参数设成 13,由于字母表的长度为 26,故 ROT13 既是加密算法,也是解密算法:
ROT13(ROT13(s))=s
ROT13(ROT13( s )) = s
ROT13(ROT13(s))=s