Python 实现 AES 加密/解密
AES,高级加密标准(Advanced Encryption Standard)。是用来替代 DES,目前比较流行的对称加密算法。与上一篇博文提到过的 RSA 非对称算法不同,对称加密算法也就是加密和解密用相同的密钥
# -*- coding: utf-8 -*- # !/usr/bin/env python import os import sys sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '..')) import json import rsa import requests import time import uuid from Crypto.Cipher import AES import base64 BLOCK_SIZE = AES.block_size pad = lambda s: s + (BLOCK_SIZE - len(s.encode()) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s.encode()) % BLOCK_SIZE) unpad = lambda s: s[:-ord(s[len(s) - 1:])] def sign_data_with_rsa(private_key, unsigned, digest_alg): pri_key = rsa.PrivateKey.load_pkcs1(open(private_key).read()) signature = rsa.sign(unsigned, pri_key, hash_method=digest_alg) return base64.b64encode(signature) def aesEncrypt(secret, data): ''' AES的MODE_CBC模式加密方法 :param key: 密钥 :param data:被加密字符串(明文) :return:密文 ''' key = secret[0:24].encode('utf-8') IV = secret[24:].encode('utf-8') # 字符串补位 data = pad(data) cipher = AES.new(key, mode=AES.MODE_CBC, IV=IV) # 加密后得到的是bytes类型的数据,使用Base64进行编码,返回byte字符串 result = cipher.encrypt(data.encode()) encodestrs = base64.b64encode(result) enctext = encodestrs.decode('utf-8') print(enctext) return enctext def decrypt_aes(sSrc, key, iv): """ AES 解密 :param sSrc: :param key: :param iv: :return: """ try: raw = key.encode('ASCII') skey_spec = AES.new(raw, AES.MODE_CBC, iv.encode()) encrypted = base64.b64decode(sSrc) original = skey_spec.decrypt(encrypted) return original.decode("utf-8") except Exception as e: print(e) raise e if __name__ == "__main__": # 测试服 appid 和secret secret = 'xxxxx' appid = "xxxxxxxx" url = "https://xxxx.test.xxxxx.com/xxxv1" nonce = str(uuid.uuid4()).replace("-", "") timestamp = time.strftime("%Y-%m-%d %H:%M:%S") req_data = { "appid": "xxxx".encode("utf-8"), # 测试app_id "biz_data": "".encode("utf-8"), "sign_type": "SHA256".encode("utf-8"), # "encrypt_data": "ENCRYPTDATA".encode("utf-8"), # 此字段为加密内容 获取用户信息无需填写,如果要填写必须做加密 "encrypt_data": "", "sign": "", "timestamp": timestamp.encode("utf-8"), "encrypt_type": "AES".encode("utf-8"), "nonce": nonce.encode("utf-8") } data = { "data": {"Info": {"OpenId": "xxxxxxx", "UserIdType": 0, "ClientId": "xxxxxxx", "Remark": "", "IsInvoice": 0, "TotalQty": "5.00", "TotalValue": "495.00", "SettlementValue": "495.00", "FreightFee": 0, "ExternalBillNo": "22062510297975", "OrgId": "0200000893", "OrderProductModelList": "[{\"supplierProductCode\":1000046232\"supplierProductName\":\"测试手镯\"\"seqNo\":0\"price\":2,\"settlementPrice\":2,\"qty\":1\"totalValue\":2\"settlementTotalValue\":2,\"imgNormalUrl\":\"a55092a9d5c6475f99415d44eff970769900002720171115\"}]"}}} message = json.dumps(data, separators=(',', ':')) req_data["encrypt_data"] = aesEncrypt(secret, message).encode("utf-8") # AES 采用CBC方式加密 kv = [str(req_data[k]) for k in sorted(req_data.keys()) if req_data[k]] if len(kv): unsigned = "@".join(kv) else: unsigned = '' unsigned = unsigned.encode("utf-8") pri_full_path = "/tmp/test_private_key2.pem" print "unsigned:", unsigned sign = sign_data_with_rsa(pri_full_path, unsigned, digest_alg="SHA-256") # 采用SHA-256方式做签名 print "sign:", sign req_data["sign"] = sign.encode("utf-8") res = requests.post(url=url, json=req_data) print res.text # {"biz_content":"","biz_encrypt":"OL/TjVRqKAclNXYaPEw6ZC3qZ5Z6zD4SIlsx4M0c6g9p+uFMJ+86sdQpZ0NVUFILDIqrkxob7YTZIrJcf5egtk3SpTskiY9C4V1VvGTGA8k=","code":"0000","msg":"sccuess","responseid":"20240305183213591124668","sign":"FA1wZKBplc8jeeBJ9ioZqSA77nRmkrkW7XjY2hmW96KcRdvxbwCAEm0Ap4oJj6HWk/IYSPJkhDFKGauKF5M+8fqadvbvc161Eh6Oz7yMpPcE28BlrFdHiayylrNaXVuzEktclptXyt4vGasjMU9FTww4WkMFzNf6PLUDjxSWtJ8mvGs2tock9T2ZCgLzWTkn8IFpdE6YRquibBWu5LQvevGDQygfSEEZh73nhyjsg0IArDlNmhunZDU9g7aR3Zobk60L0IRxhQOhVHHR2LYc09f1u5/VQ0C+QFe2LOvLojSyuTQegifwI68IicXVTGaUCEobb6wQ9fWvVUvFM0YEkQ=="} data = decrypt_aes( "OL/TjVRqKAclNXYaPEw6ZC3qZ5Z6zD4SIlsx4M0c6g9p+uFMJ+86sdQpZ0NVUFILDIqrkxob7YTZIrJcf5egtk3SpTskiY9C4V1VvGTGA8k=", secret[:24], secret[24:]) # AES 解密 print data