Python 密码学:矩阵、加法、乘法和仿射密码实现
import numpy as np
def matrix_encrypt(plain_text, key): ' 将明文转成矩阵形式 ' plain_matrix = np.array(list(plain_text)).reshape(-1, key.shape[0]) ' 对矩阵进行乘法运算 ' cipher_matrix = np.dot(plain_matrix, key) % 26 ' 将加密后的矩阵转成字符串形式 ' cipher_text = ''.join([chr(c + 65) for c in cipher_matrix.flatten()]) return cipher_text
def matrix_decrypt(cipher_text, key): ' 将密文转成矩阵形式 ' cipher_matrix = np.array(list(cipher_text)).reshape(-1, key.shape[1]) ' 对矩阵进行乘法运算 ' plain_matrix = np.dot(cipher_matrix, np.linalg.inv(key)) % 26 ' 将解密后的矩阵转成字符串形式 ' plain_text = ''.join([chr(c + 65) for c in plain_matrix.flatten()]) return plain_text
' 加法密码: '
def additive_encrypt(plain_text, key): ' 将明文转成数字序列 ' plain_nums = [ord(c) - 65 for c in plain_text] ' 对数字序列进行加法运算 ' cipher_nums = [(n + key) % 26 for n in plain_nums] ' 将加密后的数字序列转成字符串形式 ' cipher_text = ''.join([chr(c + 65) for c in cipher_nums]) return cipher_text
def additive_decrypt(cipher_text, key): ' 将密文转成数字序列 ' cipher_nums = [ord(c) - 65 for c in cipher_text] ' 对数字序列进行加法运算 ' plain_nums = [(n - key) % 26 for n in cipher_nums] ' 将解密后的数字序列转成字符串形式 ' plain_text = ''.join([chr(c + 65) for c in plain_nums]) return plain_text
' 乘法密码: '
def multiplicative_encrypt(plain_text, key): ' 将明文转成数字序列 ' plain_nums = [ord(c) - 65 for c in plain_text] ' 对数字序列进行乘法运算 ' cipher_nums = [(n * key) % 26 for n in plain_nums] ' 将加密后的数字序列转成字符串形式 ' cipher_text = ''.join([chr(c + 65) for c in cipher_nums]) return cipher_text
def multiplicative_decrypt(cipher_text, key): ' 将密文转成数字序列 ' cipher_nums = [ord(c) - 65 for c in cipher_text] ' 求逆元 ' inv_key = np.linalg.inv(np.array([[key, 1], [0, 1]])) % 26 ' 对数字序列进行乘法运算 ' plain_nums = [int(np.dot(np.array([n, 1]), inv_key) % 26) for n in cipher_nums] ' 将解密后的数字序列转成字符串形式 ' plain_text = ''.join([chr(c + 65) for c in plain_nums]) return plain_text
' 仿射密码: '
def affine_encrypt(plain_text, key): ' 将明文转成数字序列 ' plain_nums = [ord(c) - 65 for c in plain_text] ' 对数字序列进行仿射变换 ' cipher_nums = [(key[0] * n + key[1]) % 26 for n in plain_nums] ' 将加密后的数字序列转成字符串形式 ' cipher_text = ''.join([chr(c + 65) for c in cipher_nums]) return cipher_text
def affine_decrypt(cipher_text, key): ' 将密文转成数字序列 ' cipher_nums = [ord(c) - 65 for c in cipher_text] ' 求逆元 ' inv_key = np.linalg.inv(np.array([[key[0], 1], [0, 1]])) % 26 ' 对数字序列进行仿射变换 ' plain_nums = [int(np.dot(np.array([n - key[1], 1]), inv_key) % 26) for n in cipher_nums] ' 将解密后的数字序列转成字符串形式 ' plain_text = ''.join([chr(c + 65) for c in plain_nums]) return plain_text
' 使用tkinter库制作软件,不用class内容: ' import tkinter as tk from functools import partial import numpy as np
' 矩阵加密函数 ' ' ... (代码相同) ... '
' 界面设计函数 ' ' ... (代码相同) ... '
' 加密函数 ' ' ... (代码相同) ... '
' 解密函数 ' ' ... (代码相同) ... '
' 运行界面设计函数 ' gui()
AI 优化版
原文地址:https://www.cveoy.top/t/topic/ouua 著作权归作者所有。请勿转载和采集!