Python3.7基于pycryptodome的AES加密解密
安装pycryptodome模块
pip install pycryptodome
AES加密实现
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto.Random import get_random_bytes
def aes_encrypt(plain_text, key):
iv = get_random_bytes(16)
cipher = AES.new(key, AES.MODE_CBC, iv)
cipher_text = cipher.encrypt(pad(plain_text.encode(), AES.block_size))
return iv + cipher_text
AES解密实现
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
def aes_decrypt(cipher_text, key):
iv = cipher_text[:16]
cipher = AES.new(key, AES.MODE_CBC, iv)
plain_text = unpad(cipher.decrypt(cipher_text[16:]), AES.block_size)
return plain_text.decode()
示例:
key = get_random_bytes(16)
plain_text = "hello world"
cipher_text = aes_encrypt(plain_text, key)
print(cipher_text)
print(aes_decrypt(cipher_text, key))
Python3.7基于pycryptodome的RSA加密解密
生成RSA密钥对
from Crypto.PublicKey import RSA
def generate_rsa_key_pair():
key = RSA.generate(2048)
return key.publickey(), key
RSA加密实现
from Crypto.Cipher import PKCS1_OAEP
def rsa_encrypt(plain_text, public_key):
cipher = PKCS1_OAEP.new(public_key)
return cipher.encrypt(plain_text.encode())
RSA解密实现
from Crypto.Cipher import PKCS1_OAEP
def rsa_decrypt(cipher_text, private_key):
cipher = PKCS1_OAEP.new(private_key)
plain_text = cipher.decrypt(cipher_text)
return plain_text.decode()
示例
public_key, private_key = generate_rsa_key_pair()
plain_text = "hello world"
cipher_text = rsa_encrypt(plain_text, public_key)
print(cipher_text)
print(rsa_decrypt(cipher_text, private_key))
Python3.7基于pycryptodome的加签验签
生成RSA密钥对
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
def generate_rsa_key_pair():
key = RSA.generate(2048)
return key.publickey(), key
RSA私钥加签
def rsa_sign(message, private_key):
h = SHA256.new(message.encode())
signature = pkcs1_15.new(private_key).sign(h)
return signature
RSA公钥验签
def rsa_verify(message, signature, public_key):
h = SHA256.new(message.encode())
try:
pkcs1_15.new(public_key).verify(h, signature)
return True
except (ValueError, TypeError):
return False
示例
public_key, private_key = generate_rsa_key_pair()
message = "hello world"
signature = rsa_sign(message, private_key)
print(signature)
print(rsa_verify(message, signature, public_key))
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python3.7 基于 pycryptodome 的AES加密解密、RSA加密解密、加签验签 - Python技术站