简单块加密算法
一、安装 numpy 包
方法如下:https://blog.youkuaiyun.com/weixin_45759918/article/details/124532318
二、需求
- 用户输入待加密的文本(英文),程序使用简单块加密算法进行加密,输出加密文本。
- 然后程序将密文进行解密,再次输出解密文本,方便用户核实和原文本是否相同。
三、代码实现
import numpy as np
# 生成随机矩阵 -> 95个字符分为 19*5 的形式
def makeMatrix():
# 生成32-126的数字,偷懒了不手打了
checkList = []
# 装填范围到checkList中(ascii码的规定可显示字符范围)
i = 32
while (i != 127):
checkList.append(i)
i += 1
# 生成一个一维矩阵。括号中意义->(从checkList数组中,找到95个数,且不重复) 找95个数就是全找一遍。
data = np.random.choice(checkList, size=95, replace=False)
# 创建一个9行15列的二维矩阵,填充内容为'k'
# 这里不用np.zero()的原因是:np.zero()生成的数会有浮点去掉比较麻烦。
words = np.full((5, 19), 'k')
# 用于遍历data中的数
x = 0
# 循环将data中生成随机数输入words的二维矩阵。
for i in range(5):
for j in range(19):
# 随机的数字直接转为字符
words[i, j] = chr(int(data[x]))
x += 1
print(f"加密密码本为:\n{words}")
return words
# 将输入的字符分割为两两一组的二维矩阵
def segmentationText(text):
# 分割为一维数组
textList = list(text)
# 如果输入的内容拆分后不为偶数,则给其末尾加个空格。
if len(textList) % 2 != 0:
textList.append(" ")
data = []
for index in range(0, len(textList), 2):
data.append(textList[index:index + 2])
data = np.array(data)
# print(f"分割后数据为:\n{data}")
return data
# 加密过程
# 块加密:生成一个随机的acsii可视范围的密码本(二维矩阵),然后将明文分为两个字母一组的二维矩阵
# 设[A,B],其在二维矩阵的密码本中位置为 A(i,j),B(x,y)
# 如果其在密码本中同一列或同行,则互换内容 加密后为[C,D]其中 C(x,y),D(i,j) 等价于加密后密文为 [B,A]
# 若不在同行同列,则加密后为[C,D]其中 C(x,j),D(i,y) 等价于横坐标不变纵坐标变为对方纵坐标
def encryption(words, data, text):
# 密文
cipher = []
for i in range(len(data)):
A = data[i, 0]
B = data[i, 1]
Ax, Ay, Bx, By = 0, 0, 0, 0
# 找到密码本中需要加密的文字的横纵坐标
for x in range(5):
for y in range(19):
if words[x, y] == A:
Ax = int(x)
Ay = int(y)
elif words[x, y] == B:
Bx = int(x)
By = int(y)
# 判断同行同列,是则交换数据
if Ax == Bx or Ay == By:
A, B = B, A
else:
A = words[Bx, Ay]
B = words[Ax, By]
cipher.append(A)
cipher.append(B)
cipherStr = "".join(cipher)
print(f"原文为:{text}")
print(f"加密后文本为:{cipherStr}")
return cipher
# 解密,就是加密逆过程
# 同列同行交换的,换回来
# C(x,j),D(i,y)换回A(x,y),B(i,j)
def decryption(cipher, words, text):
# 密文转为二维矩阵
cipherList = segmentationText(cipher)
# 破解翻译后的明文
clear = []
for i in range(len(cipherList)):
A = cipherList[i, 0]
B = cipherList[i, 1]
Ax, Ay, Bx, By = 0, 0, 0, 0
# 找到密码本中需要加密的文字的横纵坐标
for x in range(5):
for y in range(19):
if words[x, y] == A:
Ax = int(x)
Ay = int(y)
elif words[x, y] == B:
Bx = int(x)
By = int(y)
# 判断同行同列,是则交换数据
if Ax == Bx or Ay == By:
A, B = B, A
else:
A = words[Bx, Ay]
B = words[Ax, By]
clear.append(A)
clear.append(B)
clearStr = "".join(clear)
print(f"原文为:{text}")
print(f"解密为:{clearStr}")
text = input("请输入需要加密的字符串:")
words = makeMatrix()
data = segmentationText(text)
print(f"分割后数据为:\n{data}")
cipher = encryption(words, data, text)
decryption(cipher, words, text)
显示密码本哪里和分辨率有关系或者和设置有关,但是不太碍事。