python 加解密
使用[PyCryptodome](https://www.pycryptodome.org/en/latest/)包
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
def encrypt_data_with_aes(key, plaintext):
"""
AES 加密
"""
key, plaintext = bytes(key, encoding='utf-8'), bytes(plaintext, encoding='utf-8')
cipher = AES.new(key, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(plaintext)
return cipher.nonce.hex(), ciphertext.hex(), tag.hex()
def decrypt_data_with_aes(key, nonce, ciphertext, tag):
"""
AES 解密
"""
key, nonce = bytes(key, encoding='utf-8'), bytes().fromhex(nonce)
ciphertext, tag = bytes().fromhex(ciphertext), bytes().fromhex(tag)
cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
plaintext = cipher.decrypt_and_verify(ciphertext, tag)
return str(plaintext, encoding='utf-8')
def generate_rsa_key():
"""
generate public key and private key
"""
key = RSA.generate(2048)
private_key = key.export_key()
public_key = key.publickey().export_key()
return str(public_key, encoding='utf-8'), str(private_key, encoding='utf-8')
def encrypt_data_with_rsa(public_key, message):
"""
RSA 加密
"""
public_key, message = bytes(public_key, encoding='utf-8'), bytes(message, encoding='utf-8')
recipient_key = RSA.import_key(public_key)
cipher = PKCS1_OAEP.new(recipient_key)
ciphertext = cipher.encrypt(message)
return ciphertext.hex()
def decrypt_data_with_rsa(private_key, ciphertext):
"""
RSA 解密
"""
private_key, ciphertext = bytes(private_key, encoding='utf-8'), bytes().fromhex(ciphertext)
recipient_key = RSA.import_key(private_key)
cipher = PKCS1_OAEP.new(recipient_key)
plaintext = cipher.decrypt(ciphertext)
return str(plaintext, encoding='utf-8')
def sign_with_rsa(private_key, data):
"""
RSA 签名
"""
private_key, data = bytes(private_key, encoding='utf-8'), bytes(data, encoding='utf-8')
recipient_key = RSA.import_key(private_key)
digest = SHA256.new(data)
signature = pkcs1_15.new(recipient_key).sign(digest)
return signature.hex()
def verify_with_rsa(public_key, data, signature):
"""
RSA 验签
"""
public_key, data = bytes(public_key, encoding='utf-8'), bytes(data, encoding='utf-8')
signature = bytes().fromhex(signature)
recipient_key = RSA.import_key(public_key)
digest = SHA256.new(data)
try:
pkcs1_15.new(recipient_key).verify(digest, signature)
except (ValueError, TypeError):
return False
return True