您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關(guān)Python3.7基于hashlib和Crypto實(shí)現(xiàn)加簽驗(yàn)簽功能的方法的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
環(huán)境:
Python3.7
依賴庫:
import datetime import random import requests import hashlib import json import base64 from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA256 from Crypto.Cipher import AES
加簽:
def sign(signflag,keypath,baseRequest): #http請求body print(baseRequest) #加簽標(biāo)志 if not signflag: return baseRequest else: #取請求體中的業(yè)務(wù)數(shù)據(jù) businessdata = json.dumps(baseRequest["data"]) #讀取私鑰(.key格式,可使用openssl或java.keytools產(chǎn)生) with open(keypath,'r') as rsaKeyFile: rsaKey = rsaKeyFile.read().replace("\n",'') print(rsaKey) rsaKeyBytes = base64.b64decode(rsaKey) print(rsaKeyBytes) #SHA256摘要,RSA加密 priKey = RSA.importKey(rsaKeyBytes) signer = PKCS1_v1_5.new(priKey) hash_obj = SHA256.new(business_data.encode('utf-8')) signature = base64.b64encode(signer.sign(hash_obj)) print(signature) #把簽名加進(jìn)請求體并返回 baseRequest['sign'] = signature.decode() print(baseRequest) return baseRequest
驗(yàn)簽:
def validata(signflag,cerpath,res): if not signflag: return res else: #取業(yè)務(wù)數(shù)據(jù)和簽名 data = res['data'] sign = res['sign'] #此處cer已轉(zhuǎn)換成pem格式,使用openssl工具 #openssl x509 -inform der -pubkey -noout -in xxxxx.cer>xxxxx.pem cert = open(cerpath).read().replace("-----BEGIN PUBLIC KEY-----\n","").replace("-----END PUBLIC KEY-----\n","").replace("\n","") print(cert) #驗(yàn)簽邏輯同加簽 pubBytes = base64.b64decode(cert) pubKey = RSA.importKey(pubBytes) signer = SHA256.new(json.dumps(data).encode("utf-8")) verifier = PKCS1_v1_5.new(pubKey) return verifier.verify(signer,base64.b64decode(sign))
感謝各位的閱讀!關(guān)于“Python3.7基于hashlib和Crypto實(shí)現(xiàn)加簽驗(yàn)簽功能的方法”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。