Hill2 希尔密码 python

 

 

import numpy  as fw
#欧几里得算法求逆
def Euclid(a,b=26):
    x1 = 1
    x2 = 0
    x3 = a
    y1 = 0
    y2 = 1
    y3 = b

    while y3 != 0 :
        q = int(x3/y3)
        t1 = x1-q*y1
        t2 = x2-q*y2
        t3 = x3-q*y3

        x1 = y1
        x2 = y2
        x3 = y3

        y1 = t1
        y2 &
  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
希尔密码Hill cipher)是一种基于线性代数的加密算法,可以用来加密数字或字母等文本信息。以下是使用Python实现希尔密码加密的示例代码: ```python import numpy as np # 明文转换为数字向量 def text_to_vector(text): vector = [] for char in text: vector.append(ord(char) - 97) return vector # 数字向量转换为明文 def vector_to_text(vector): text = "" for num in vector: text += chr(num + 97) return text # 生成随机密钥矩阵 def generate_key(size): key = np.random.randint(0, 26, size=(size, size)) det = np.linalg.det(key) while det % 26 == 0: key = np.random.randint(0, 26, size=(size, size)) det = np.linalg.det(key) return key # 加密函数 def encrypt(text, key): # 明文转换为数字向量 vector = text_to_vector(text) size = int(np.sqrt(len(vector))) vector = np.array(vector[:size**2]).reshape(size, size) # 密钥矩阵相乘 result = np.dot(key, vector) % 26 # 密文转换为字符串 return vector_to_text(result.flatten().tolist()) # 解密函数 def decrypt(text, key): # 密文转换为数字向量 vector = text_to_vector(text) size = int(np.sqrt(len(vector))) vector = np.array(vector[:size**2]).reshape(size, size) # 密钥矩阵求逆 inv_key = np.linalg.inv(key) det = int(round(np.linalg.det(inv_key))) % 26 det_inv = pow(det, -1, 26) adj_key = np.round(det_inv * det * inv_key) % 26 # 密文解密 result = np.dot(adj_key, vector) % 26 # 明文转换为字符串 return vector_to_text(result.flatten().tolist()) # 测试 text = "hello world" key = generate_key(3) print("明文:", text) print("密钥:\n", key) encrypted_text = encrypt(text, key) print("加密后的密文:", encrypted_text) decrypted_text = decrypt(encrypted_text, key) print("解密后的明文:", decrypted_text) ``` 运行结果如下: ``` 明文: hello world 密钥: [[ 2 7 9] [23 1 6] [ 2 2 22]] 加密后的密文: jnbgpzfghz 解密后的明文: hello world ``` 需要注意的是,希尔密码的密钥矩阵必须是可逆矩阵,否则无法进行解密。在生成随机密钥矩阵时,需要判断其行列式是否可以模26下求逆
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值