Python3.7基于hashlib和Crypto實(shí)現(xiàn)加簽驗(yàn)簽功能(實(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請(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ì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
相關(guān)文章
Python?Concurrent?Futures解鎖并行化編程的魔法示例
Python的concurrent.futures模塊為并行化編程提供了強(qiáng)大的工具,使得開發(fā)者能夠輕松地利用多核心和異步執(zhí)行的能力,本文將深入探討concurrent.futures的各個(gè)方面,從基礎(chǔ)概念到高級(jí)用法,為讀者提供全面的了解和實(shí)用的示例代碼2023-12-12
python中翻譯功能translate模塊實(shí)現(xiàn)方法
在本篇文章中小編給各位整理了一篇關(guān)于python中翻譯功能translate模塊實(shí)現(xiàn)方法,有需要的朋友們可以參考下。2020-12-12
python實(shí)現(xiàn)多線程及線程間通信的簡(jiǎn)單方法
這篇文章主要為大家介紹了python實(shí)現(xiàn)多線程及線程間通信的簡(jiǎn)單方法示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07
用python打開攝像頭并把圖像傳回qq郵箱(Pyinstaller打包)
這篇文章主要介紹了用python打開攝像頭并把圖像傳回qq郵箱,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
python讀取并繪制nc數(shù)據(jù)的保姆級(jí)教程
其實(shí)目前很多數(shù)據(jù)以nc格式存儲(chǔ),這篇文章主要給大家介紹了關(guān)于python讀取并繪制nc數(shù)據(jù)的保姆級(jí)教程,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05
Python設(shè)計(jì)模式結(jié)構(gòu)型代理模式
這篇文章主要介紹了Python設(shè)計(jì)模式結(jié)構(gòu)型代理模式,代理模式即Proxy?Pattern,為其他對(duì)象提供一種代理以控制對(duì)這個(gè)對(duì)象的訪問,下文內(nèi)容詳細(xì)介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-02-02

