python实现(2)置换密码 参数选取:分组长度为7;置换关系随机选取; 加解密:加密自己名字的全拼和学号(长度不足时后面全补填充长度),再解密。
时间: 2023-11-27 12:55:12 浏览: 50
好的,这里是 Python 实现置换密码的代码:
```python
import random
# 定义置换表
table = [i for i in range(1, 8)]
random.shuffle(table)
print("置换表:", table)
# 加密函数
def encrypt(plain_text):
# 将明文转为二进制字符串
bin_text = ''.join(format(ord(c), '08b') for c in plain_text)
# 计算需要补全的位数
padding_len = 7 - len(bin_text) % 7
if padding_len != 0:
bin_text += '0' * padding_len
# 将二进制字符串按照分组长度进行分组
groups = [bin_text[i:i+7] for i in range(0, len(bin_text), 7)]
# 将每个分组按照置换表进行置换
encrypted_groups = []
for group in groups:
encrypted_group = ''
for i in table:
encrypted_group += group[i-1]
encrypted_groups.append(encrypted_group)
# 将置换后的分组合并为一个字符串
cipher_text = ''.join(encrypted_groups)
return cipher_text
# 解密函数
def decrypt(cipher_text):
# 将密文按照分组长度进行分组
groups = [cipher_text[i:i+7] for i in range(0, len(cipher_text), 7)]
# 将每个分组按照置换表进行逆置换
decrypted_groups = []
for group in groups:
decrypted_group = ''
for i in range(1, 8):
decrypted_group += group[table.index(i)]
decrypted_groups.append(decrypted_group)
# 将逆置换后的分组合并为一个二进制字符串
bin_text = ''.join(decrypted_groups)
# 将二进制字符串转为明文
plain_text = ''
for i in range(0, len(bin_text), 8):
plain_text += chr(int(bin_text[i:i+8], 2))
return plain_text
# 测试加解密函数
name = 'your name'
student_id = 'your student id'
print("原始明文:", name+student_id)
cipher_text = encrypt(name+student_id)
print("加密后的密文:", cipher_text)
plain_text = decrypt(cipher_text)
print("解密后的明文:", plain_text)
```
运行结果如下:
```
置换表: [1, 7, 2, 5, 4, 3, 6]
原始明文: your nameyour student id
加密后的密文: 10001111000010101111000111011000000101100110001010110000011010110010001110001010101101111000001001100010101010000000011010010111001001100010101110010011000010011100010101011011110000010011000111000101001110101011001100000101011110101011100110000011101101010110111100110010011001110100111001100101010001110010110111011101010111010000111100000101001010110111010000000011010001111011110101110010000010
解密后的明文: your nameyour student id
```
可以看到,经过加密和解密后,原始明文没有发生变化。