美文网首页
用PY实现AES&RSA数据加密解密

用PY实现AES&RSA数据加密解密

作者: 报告老师 | 来源:发表于2020-07-28 10:45 被阅读0次

    # -*- encoding: utf-8 -*-

    from Crypto.Cipher import AES

    from Crypto.PublicKey import RSA

    from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcsl_v1_5

    from binascii import b2a_hex, a2b_hex

    import base64

    import urllib.parse

    import requests

    import hashlib

    import random

    import time

    import json

    BS = AES.block_size

    mode = AES.MODE_CBC

    apiUrl = '*******'

    appId = '*******'

    encry_model = 'CBC'

    appSecret = ‘*******’

    serverName = '*******'

    methodName = '*******'

    parameters = {}

    key = '0011223344556677'

    public_key = '''-----BEGIN PUBLIC KEY-----

    MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDGCJ0Yvs7keKW2lNlRHMoEFCH3

    t4jCEIYNSN8nx+AQTsBj39hmRJ1j6mgjbuo7UeXvZUq+1Vm457DvPcpuCZgZzHin

    D1jAx8M/aHar2oOJzxWjMGo+4EVuQnleeziezretVEMxAi8KFdtd28VZ2qBqasaL

    4GSP6z3qfOJ7an0OUQIDAQAB

    -----END PUBLIC KEY-----

    '''

    def getTimeStamp():#生成时间戳

        now = time.strftime("%Y%m%d%H%M%S", time.localtime())

        return now

    def randomNonce():

        L = []

        M = []

        for i in range(10):

            L.append(random.randint(0, 9))

            if len(L) >= 10:

                break

        for d in L:

            M.append(str(d))

        S = '' .join(M)

        return S

    def pad(s): return s + (BS-len(s))*'\0'  # 补全key

    def pad_txt(s): return s + (BS - len(s) % BS) * \

        chr(BS - len(s) % BS)  # 補全parameter

    def aESEncrypt(param):#aes加密

        iv = '0102030405060708'#偏移量

        cipher = AES.new(pad(key).encode('utf-8'), mode, iv.encode('utf-8'))

        parameter_string = cipher.encrypt(pad_txt(param).encode('utf-8'))

        parameter_string1 = base64.b64encode(parameter_string)

        parameter_string2 = str(parameter_string1)

        return parameter_string2

    def rSAEncrypt(key, publickey):

        rsakey = RSA.import_key(publickey)

        cipher = Cipher_pkcsl_v1_5.new(rsakey)

        cipher_text1 = base64.b64encode(cipher.encrypt(key.encode('utf-8')))

        encry_key = str(cipher_text1)

        return encry_key

    def getSignature(params, appSecret):#计算签名

        signature = ''

        query = ''

        temps = []

        for key in params.keys():

            temps.append(key)

        temps.sort()

        for temp in temps:

            query += '&'+temp+'='+urllib.parse.quote(params[temp],safe='')

        query2 = query[1:]+'&'+appSecret

        sha = hashlib.sha1(query2.encode('utf-8'))

        signature = sha.hexdigest()

        return signature

    def getApiParams(appId,serverName,methodName,parameters,encryKey,appSecret,publicKey):#生成请求参数

        cipher_encry_key_encode = rSAEncrypt(encryKey,publicKey)

        cipher_parameters_encode = aESEncrypt(parameters)

        params={

            'app_id':appId,

            'server_name':serverName,

            'encry_mode':'RSA',

            'encry_key':cipher_encry_key_encode.strip("b'"),

            'timestamp':getTimeStamp(),

            'nonce':randomNonce(),

            'method':methodName,

            'parameters':cipher_parameters_encode.strip("b'")

        }

        signature = getSignature(params,appSecret)

        params['signature'] = signature

        return params

    def aESDecrypt(cipherText):#aes解密

        key = '0011223344556677'.encode('utf-8')

        iv = '0102030405060708'.encode('utf-8')

        mode = AES.MODE_CBC

        cryptos = AES.new(key, mode, iv)

        base64_decrypted = base64.decodebytes(cipherText.encode(encoding='utf-8'))

        decrypted_text = str(cryptos.decrypt(base64_decrypted),encoding='utf-8').replace('\0','')

        return decrypted_text

    def pyPost(key, apiUrl, appId, appSecret, publicKey, serverName, methodName, parameters):

        paramString = json.dumps(parameters)

        dataforpost = getApiParams(appId,serverName,methodName,paramString,key,appSecret,public_key)

        res = requests.post(url=apiUrl,data=dataforpost)

        res_body = json.loads(res.text)['res_body']

        decoded_res_body = urllib.parse.unquote(res_body)

        clear_text = aESDecrypt(decoded_res_body)

        return clear_text

    resp = pyPost(key,apiUrl,appId,appSecret,public_key,serverName,methodName,parameters)

    print(resp)

    相关文章

      网友评论

          本文标题:用PY实现AES&RSA数据加密解密

          本文链接:https://www.haomeiwen.com/subject/hftfrktx.html