Python3.7基于hashlib和Crypto實現(xiàn)加簽驗簽功能(實例代碼)
更新時間:2019年12月04日 10:38:38 作者:clkai
這篇文章主要介紹了Python3.7基于hashlib和Crypto實現(xiàn)加簽驗簽功能,環(huán)境是基于python3.7,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
環(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) #加簽標志 if not signflag: return baseRequest else: #取請求體中的業(yè)務數(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) #把簽名加進請求體并返回 baseRequest['sign'] = signature.decode() print(baseRequest) return baseRequest
驗簽:
def validata(signflag,cerpath,res): if not signflag: return res else: #取業(yè)務數(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) #驗簽邏輯同加簽 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))
總結
以上所述是小編給大家介紹的Python3.7基于hashlib和Crypto實現(xiàn)加簽驗簽功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關文章
Tensorflow實現(xiàn)部分參數(shù)梯度更新操作
今天小編就為大家分享一篇Tensorflow實現(xiàn)部分參數(shù)梯度更新操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01解決Python3.8運行tornado項目報NotImplementedError錯誤
這篇文章主要介紹了Python3.8運行tornado項目報NotImplementedError錯誤,本文給大家分享解決方法,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09tensorflow 動態(tài)獲取 BatchSzie 的大小實例
這篇文章主要介紹了tensorflow 動態(tài)獲取 BatchSzie 的大小實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06