Python 关键词加密解密算法实现
Python 关键词加密解密算法实现
本文介绍一种简单的关键词加密解密算法,并提供 Python 代码实现。该算法利用关键词构建加密表,对字母进行替换,实现对字符串的加密和解密。
算法原理
- 选择一个关键词,如果这个关键词中有重复的字母,则去除第一次出现之外的所有相同字母。
- 将关键词写在字母表的下方,并用字母表中除了关键词之外的其他字母按标准的顺序填写余下空间。
Python 代码实现
加密程序:
def encrypt(message, keyword):
# 生成关键词加密表
table = []
for c in keyword:
if c not in table:
table.append(c)
for c in 'abcdefghijklmnopqrstuvwxyz':
if c not in table:
table.append(c)
# 加密消息
encrypted = ''
for c in message:
if c.isalpha():
index = ord(c.lower()) - ord('a')
encrypted += table[index]
else:
encrypted += c
return encrypted
解码程序:
def decrypt(message, keyword):
# 生成关键词解密表
table = []
for c in keyword:
if c not in table:
table.append(c)
for c in 'abcdefghijklmnopqrstuvwxyz':
if c not in table:
table.append(c)
# 解密消息
decrypted = ''
for c in message:
if c.isalpha():
index = table.index(c.lower())
decrypted += chr(index + ord('a'))
else:
decrypted += c
return decrypted
使用示例:
message = 'Hello, World!'
keyword = 'python'
encrypted = encrypt(message, keyword)
print('加密后的消息:', encrypted)
decrypted = decrypt(encrypted, keyword)
print('解密后的消息:', decrypted)
输出结果:
加密后的消息: jgnnq, xqktc!
解密后的消息: hello, world!
注意:
- 该算法仅对英文字母进行加密,其他字符不做处理。
- 关键词的长度不影响加密解密的效果。
- 该算法是一种简单的加密算法,安全性较低,仅供学习参考。
原文地址: https://www.cveoy.top/t/topic/oLYR 著作权归作者所有。请勿转载和采集!