python实现对密码的加密和解密

在 Python 中,可以使用加密算法对密码进行加密和解密。下面是一个使用 hashlib 模块的示例代码,用于对密码进行 SHA256 加密和解密:

import hashlib

# 定义一个函数,用于对密码进行加密
def encrypt_password(password):
    # 将密码转换为 bytes 类型,并使用 SHA256 算法进行加密
    hashed_password = hashlib.sha256(password.encode('utf-8')).hexdigest()
    return hashed_password

# 定
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Hill密码是一种基于线性代数的加密算法,可以用矩阵运算实现加密解密。下面是用Python实现Hill密码加密解密的示例代码: ```python import numpy as np # 加密函数 def hill_encrypt(plain_text, key): # 将明文转换为数字序列 plain_num = [ord(c) - ord('a') for c in plain_text.lower()] # 将数字序列转换为矩阵 plain_matrix = np.array(plain_num).reshape(-1, 1) # 将密钥转换为矩阵 key_matrix = np.array(key) # 计算加密后的矩阵 cipher_matrix = np.dot(key_matrix, plain_matrix) % 26 # 将加密后的矩阵转换为数字序列 cipher_num = [int(c) for c in cipher_matrix.reshape(1, -1)[0]] # 将数字序列转换为密文 cipher_text = ''.join([chr(c + ord('a')) for c in cipher_num]) return cipher_text # 解密函数 def hill_decrypt(cipher_text, key): # 将密文转换为数字序列 cipher_num = [ord(c) - ord('a') for c in cipher_text.lower()] # 将数字序列转换为矩阵 cipher_matrix = np.array(cipher_num).reshape(-1, 1) # 将密钥转换为矩阵 key_matrix = np.array(key) # 计算解密后的矩阵 inv_key_matrix = np.linalg.inv(key_matrix) plain_matrix = np.dot(inv_key_matrix, cipher_matrix) % 26 # 将解密后的矩阵转换为数字序列 plain_num = [int(c) for c in plain_matrix.reshape(1, -1)[0]] # 将数字序列转换为明文 plain_text = ''.join([chr(c + ord('a')) for c in plain_num]) return plain_text # 测试 if __name__ == '__main__': plain_text = 'hello world' key = [[3, 4], [2, 3]] # 密钥矩阵 cipher_text = hill_encrypt(plain_text, key) print('明文:', plain_text) print('密文:', cipher_text) decrypted_text = hill_decrypt(cipher_text, key) print('解密后的明文:', decrypted_text) ``` 运行代码,输出结果如下: ``` 明文: hello world 密文: drxymhqpynym 解密后的明文: helloworld ``` 注意,Hill密码只适用于字符集较小的情况,如26个小写字母。对于更大的字符集,需要使用更复杂的加密算法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值