简述

置换密码是一种不改变明文字符、只改变字符顺序的加密算法。

加解密:

给出明文字符串,如 abcde,则此时的排序记为 [1,2,3,4,5]
给定一个随机序列作为密钥,如 [2,1,4,5,3]

  • 加密

将原始字符串的字符位置,按照密钥的排序位置改变,重新组合。

初始序列:[1,2,3,4,5]
置换序列:[2,1,4,5,3]

上述加密结果:[b,a,d,e,c]

  • 解密

将密文序列进行一次密钥的逆置换,即得明文。

初始序列:[1,2,3,4,5]
置换序列:[2,1,4,5,3]
逆置序列:[2,1,5,3,4]

上述解密结果:[1,2,3,4,5][a,b,c,d,e]

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/python3.7
# -*- coding: utf-8 -*-
# @Time : 2019/12/11 15:03
# @Software: PyCharm

from random import randrange, shuffle

# 生成消息分组
def inputMassage(massage, keyLength):
massageList = []
# 扩充消息序列并创建分组
while len(massage) % keyLength != 0:
massage += " "
for i in range(1, len(massage) + 1, keyLength):
massageList.append(massage[i-1:i + keyLength - 1])
return massageList

# 生成密钥
def createKey(keyLength):
# 方法生成
# keyList = [i for i in range(1, keyLength + 1)]
# shuffle(keyList) # 生成随机排序
# 手工生成
keyList = []
while len(keyList) < keyLength:
for i in range(1, keyLength + 1):
key = randrange(1, keyLength + 1)
if key not in keyList:
keyList.append(key)
return keyList

# 加密
def encrypt(massage, keyList):
ciphertext = ""
# 创建明文分组
massageList = inputMassage(massage, keyLength)
for item in massageList:
# 存储改变字母位置后的临时列表
itemList = [0 for i in range(len(keyList))]
for i in range(len(keyList)):
itemList[i] = list(item)[keyList[i] - 1]
ciphertext += itemList[i]
return ciphertext

# 解密
def decrypt(massage, keyList):
plaintext = ""
plaintextList = inputMassage(massage, keyLength)
for item in plaintextList:
# 存储改变字母位置后的临时列表
itemList = [0 for i in range(len(keyList))]
for i in range(len(keyList)):
itemList[keyList[i] - 1] = list(item)[i]
for i in itemList:
plaintext += str(i)
return plaintext

if __name__ == "__main__":
while True:
print("—————置换密码—————")
choice = input("1、加密 2、解密\n请选择:")
if choice == "1":
massage = input("输入明文序列:")
keyLength = int(input("输入分组长度:"))
keyList = createKey(keyLength)
print("密钥分组:", keyList)
ciphertext = encrypt(massage, keyList)
print("密文结果:", ciphertext)
elif choice == "2":
massage = input("输入密文序列:")
keyList = list(map(int, list(input("输入密钥序列:").split(","))))
plaintext = decrypt(massage, keyList)
print("明文:", plaintext)

结果测试

在这里插入图片描述