1.安装crypto库
pip install pycryptodome
ps:
使用pip工具安装步骤:
1、直接安装pycryptodome模块即可
pip install pycryptodome
2、如果你已经通过pip install crypto命令安装了,那么需要做以下两步:
(1)切换到python安装目录的liib\site-packages目录下,将crypto目录名称修改为Crypto,即将首字母小写改成大写。
(2)安装pycryptodome,使用命令pip install pycryptodome。安装pycryptodome后Crypto目录会多出很多实际程序要用到的文件目录。
2.实现AES的加密解密
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
def encrypt(plain_text, key):
iv = get_random_bytes(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
cipher_text = cipher.encrypt(pad(plain_text, AES.block_size))
return iv + cipher_text
def decrypt(cipher_text, key):
iv = cipher_text[:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
plain_text = unpad(cipher.decrypt(cipher_text[AES.block_size:]), AES.block_size)
return plain_text
key = get_random_bytes(16) # 16字节(128位)的随机密钥
plain_text = b'hello world'
cipher_text = encrypt(plain_text, key)
decrypted_text = decrypt(cipher_text, key)
print('Plain text:', plain_text)
print('Decrypted text:', decrypted_text)
不过要注意的是,在pycharm使用需要注意,直接import Crypto会报错,因为安装后再文件夹内的文件名是crypto,全是小写,而我们直接import crypto也是会出错,需要我们手动修改库文件名字为Crypto,参考文章:
https://blog.csdn.net/weixin_44133008/article/details/107102575文章来源:https://www.toymoban.com/news/detail-740526.html
3.实现3DES加密解密
from Crypto.Cipher import DES3
from Crypto.Util.Padding import pad, unpad
# 加密函数
def encrypt(key, plaintext):
# 创建3DES加密器
cipher = DES3.new(key, DES3.MODE_ECB)
# 填充明文
plaintext = pad(plaintext, DES3.block_size)
# 加密明文
ciphertext = cipher.encrypt(plaintext)
return ciphertext
# 解密函数
def decrypt(key, ciphertext):
# 创建3DES解密器
cipher = DES3.new(key, DES3.MODE_ECB)
# 解密密文
plaintext = cipher.decrypt(ciphertext)
# 去除填充
plaintext = unpad(plaintext, DES3.block_size)
return plaintext
# 示例用法
key = b"0123456789abcdef"
plaintext = b"Hello, world!"
ciphertext = encrypt(key, plaintext)
decrypted_plaintext = decrypt(key, ciphertext)
print("明文:", plaintext)
print("密文:", ciphertext)
print("解密后明文:", decrypted_plaintext)
4.通过cryptography库实现3DES加密解密
其中需要指定加密方式为CBC,补码方式为PKCS7,不过以下代码解密后的内容有部分为乱码,有待解决。文章来源地址https://www.toymoban.com/news/detail-740526.html
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import os
# 3DES加密函数
def des_3_encrypt(data, key):
# 创建3DES加密器
cipher = Cipher(algorithms.TripleDES(key), modes.CBC(os.urandom(8)), backend=default_backend())
# 加密数据
encryptor = cipher.encryptor()
padded_data = pad(data, 8, style='pkcs7')
encrypted_data = encryptor.update(padded_data) + encryptor.finalize()
return encrypted_data
# 3DES解密函数
def des_3_decrypt(data, key):
# 创建3DES解密器
cipher = Cipher(algorithms.TripleDES(key), modes.CBC(os.urandom(8)), backend=default_backend())
# 解密数据
decryptor = cipher.decryptor()
decrypted_data = decryptor.update(data) + decryptor.finalize()
unpadded_data = unpad(decrypted_data, 8, style='pkcs7')
return unpadded_data
# PKCS7补码函数
def pad(data, block_size, style='pkcs7'):
padding_size = block_size - len(data) % block_size
padding = bytes([padding_size] * padding_size)
if style == 'pkcs7':
return data + padding
elif style == 'x923':
return b'\x80' + data + padding
else:
raise ValueError('Invalid padding style')
# PKCS7去码函数
def unpad(data, block_size, style='pkcs7'):
if style == 'pkcs7':
padding_size = data[-1]
elif style == 'x923':
padding_size = data[-1]
if padding_size > block_size:
raise ValueError('Invalid padding')
if data[-padding_size:]!= bytes([padding_size] * padding_size):
raise ValueError('Invalid padding')
else:
raise ValueError('Invalid padding style')
return data[:-padding_size]
key = b"0123456789abcdef"
data = b"01234567890ABCDEF"
encrypted_data = des_3_encrypt(data, key)
decrypted_data = des_3_decrypt(encrypted_data, key)
print("Original data:", data)
print("Encrypted data:", encrypted_data)
print("Decrypted data:", decrypted_data)
print(decrypted_data.decode("ascii"))
到了这里,关于python基于crypto实现加密与解密的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!