Python中的加密解密库使用方法
发布时间:2023-07-02 10:21:04
在Python中,有一些非常常用的加密解密库,如hashlib、cryptography、rsa、pycryptodome等等。下面将介绍这几个库的使用方法。
1. hashlib库
hashlib库提供了一些非对称加密算法和散列函数,例如MD5、SHA1、SHA256等等。使用该库进行加密解密的一般步骤如下:
# 导入hashlib库 import hashlib # 创建hash对象 h = hashlib.sha256() # 将数据添加到hash对象中 h.update(b"Hello World") # 获取加密后的结果 encrypted_data = h.hexdigest() print(encrypted_data)
2. cryptography库
cryptography库是Python中一个功能较为强大的加密解密库,提供了对称加密、非对称加密、数字签名、密码哈希等功能。使用该库进行加密解密的一般步骤如下:
# 导入cryptography库 from cryptography.fernet import Fernet # 生成密钥 key = Fernet.generate_key() # 创建Fernet对象 cipher_suite = Fernet(key) # 加密数据 encrypted_data = cipher_suite.encrypt(b"Hello World") # 解密数据 decrypted_data = cipher_suite.decrypt(encrypted_data) print(encrypted_data) print(decrypted_data)
3. rsa库
rsa库是Python中一个用于进行RSA加密解密的库,使用该库进行加密解密的一般步骤如下:
# 导入rsa库 import rsa # 生成密钥对 (pubkey, privkey) = rsa.newkeys(1024) # 加密数据 encrypted_data = rsa.encrypt(b"Hello World", pubkey) # 解密数据 decrypted_data = rsa.decrypt(encrypted_data, privkey) print(encrypted_data) print(decrypted_data)
4. pycryptodome库
pycryptodome库是Python中一个功能齐全的加密解密库,包含了很多加密算法和协议。使用该库进行加密解密的一般步骤如下:
# 导入pycryptodome库 from Crypto.Cipher import AES # 生成密钥和初始向量 key = b"1234567890123456" iv = b"1234567890123456" # 创建AES对象 cipher = AES.new(key, AES.MODE_CBC, iv) # 加密数据 encrypted_data = cipher.encrypt(b"Hello World") # 解密数据 decrypted_data = cipher.decrypt(encrypted_data) print(encrypted_data) print(decrypted_data)
以上是常用的几个加密解密库的使用方法,你可以根据自己的需求选择适合的库来进行加密解密操作。
