Python3.7基于hashlib和Crypto實(shí)現(xiàn)加簽驗(yàn)簽功能(實(shí)例代碼)
環(huán)境:
Python3.7
依賴(lài)庫(kù):
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請(qǐng)求body
print(baseRequest)
#加簽標(biāo)志
if not signflag: return baseRequest
else:
#取請(qǐng)求體中的業(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)請(qǐng)求體并返回
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))
總結(jié)
以上所述是小編給大家介紹的Python3.7基于hashlib和Crypto實(shí)現(xiàn)加簽驗(yàn)簽功能,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
相關(guān)文章
Tensorflow實(shí)現(xiàn)部分參數(shù)梯度更新操作
今天小編就為大家分享一篇Tensorflow實(shí)現(xiàn)部分參數(shù)梯度更新操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-01-01
解決Python3.8運(yùn)行tornado項(xiàng)目報(bào)NotImplementedError錯(cuò)誤
這篇文章主要介紹了Python3.8運(yùn)行tornado項(xiàng)目報(bào)NotImplementedError錯(cuò)誤,本文給大家分享解決方法,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-09-09
tensorflow 動(dòng)態(tài)獲取 BatchSzie 的大小實(shí)例
這篇文章主要介紹了tensorflow 動(dòng)態(tài)獲取 BatchSzie 的大小實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06
python?與c++相互調(diào)用實(shí)現(xiàn)
這篇文章主要介紹了python?與c++相互調(diào)用實(shí)現(xiàn),我們都知道c++運(yùn)算速度快于python,python又簡(jiǎn)單易寫(xiě),很多人就會(huì)想到將兩者結(jié)合,接下倆小編要給大家介紹的就是python?與c++相互調(diào)用實(shí)現(xiàn),,需要的朋友可以參考一下2022-03-03
Python高階函數(shù)map()?簡(jiǎn)介和使用詳解
map()?函數(shù)是Python中的內(nèi)置函數(shù),這個(gè)函數(shù)又叫做映射函數(shù),其實(shí)里面具有一個(gè)迭代器的功能,會(huì)依次遍歷可迭代對(duì)象進(jìn)行相關(guān)的操作,這篇文章主要介紹了Python高階函數(shù)map()?簡(jiǎn)介和使用詳解,需要的朋友可以參考下2023-03-03

