凯撒密码原理
密码进行平移对应,比如k1中的a对应k2的D,b对应E…构建一个k1对应k2的查询表。
我们可以用下方的形式表示:
函数对应关系为:拥有这个函数对应关系,我们可以很简单地写出代码
凯撒密码加密的python实现
假设我们要对"ATTACK"这个字符串进行凯撒密码转换,那么我们需要创建一个查询表,使得其原字母对应到另一个密码表上。
创建新的字典
那么我们要使用到string.ascii_letters
,这个函数是有什么作用呢?
可以看到其作用,假设我们只需要大写的字母:
随后,我们利用公式创建新的查询表:
import string
message = "ATTACK"
# shift = 3
# A ->
# T ->
# C ->
# K ->
cipher_text = ""
letters = string.ascii_letters[26:]
key = {}
shift = 3
i = 0
for c in letters:
key[c] = letters[(i+shift) % 26] #产生新的字典
i = i + 1
print(key)
运行结果如下:
随后,我们可以通过查询这个字典进行加密。
用以下几行代码实现:
cipher_text = ""
for c in message:
cipher_text += key[c]
print(cipher_text)
输出结果为:DWWDFN
加密代码
将代码一般化获得:
import string
def generate_key(shift):
letters = string.ascii_letters[26:]
key = {}
i = 0
for c in letters:
key[c] = letters[(i+shift) % len(letters)]
i = i + 1
return key
def encrypt(key, message):
cipher = ""
for c in message:
cipher += key[c]
print(cipher)
return cipher
key = generate_key(3)
message = "ATTACK"
cipher_code = encrypt(key, message)
凯撒密码解密的python实现
def get_decryption_key(shift):
letters = string.ascii_letters[26:]
key = {}
i = 0
for c in letters:
# key[c] = letters[(i-shift+len(letters)) % len(letters)]
key[letters[(i+shift) % len(letters)]] = c
i = i + 1
# print(key)
return key
def decrypt(key, message):
plain_text = ""
for c in message:
plain_text += key[c]
print(plain_text)
return plain_text
测试结果:
思考
凯撒密码的安全性问题:
基于已有的字母表进行一个偏移,生成一个加密的字母表,这个偏移的大小有一定的范围(不可能大于26)。
导致生成加密的密钥有限,容易被暴力破解。