Python 加密与解密

安装 pycryptodome

pip install pycryptodome

案例

import json
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
from Crypto import Random

# 定义加密函数

def encrypt_license(license_data, key):
    cipher = AES.new(key, AES.MODE_CBC)
    plaintext = json.dumps(license_data).encode('utf-8')
    ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))
    iv = cipher.iv
    encrypted_license = iv + ciphertext
    return encrypted_license

# 定义解密函数

def decrypt_license(encrypted_license, key):
    cipher = AES.new(key, AES.MODE_CBC, iv=encrypted_license[:16])
    ciphertext = encrypted_license[16:]
    plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size).decode('utf-8')
    decrypted_license = json.loads(plaintext)
    return decrypted_license
    
    
def test():
    # 定义许可证数据
    license_data = {
        "username": "testuser",
        "expiration_time": "2022-01-01"
    }
    # 定义密钥
    key = get_random_bytes(16)
    # 加密许可证
    encrypted_license = encrypt_license(license_data, key)
    # 将加密后的许可证写入文件
    with open(r'F:\env\licence\encrypted_license.bin', 'wb') as f:
        f.write(encrypted_license)
    # 读取加密后的许可证
    with open(r'F:\env\licence\encrypted_license.bin', 'rb') as f:
        encrypted_license = f.read()
    # 解密许可证
    decrypted_license = decrypt_license(encrypted_license, key)
    # 检查解密后的许可证是否正确
    assert 
    == license_data
    print("许可证正确")
    return True
test()