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已轉換成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)站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
相關文章
Python?Concurrent?Futures解鎖并行化編程的魔法示例
Python的concurrent.futures模塊為并行化編程提供了強大的工具,使得開發(fā)者能夠輕松地利用多核心和異步執(zhí)行的能力,本文將深入探討concurrent.futures的各個方面,從基礎概念到高級用法,為讀者提供全面的了解和實用的示例代碼2023-12-12
python中翻譯功能translate模塊實現(xiàn)方法
在本篇文章中小編給各位整理了一篇關于python中翻譯功能translate模塊實現(xiàn)方法,有需要的朋友們可以參考下。2020-12-12
用python打開攝像頭并把圖像傳回qq郵箱(Pyinstaller打包)
這篇文章主要介紹了用python打開攝像頭并把圖像傳回qq郵箱,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-05-05
python讀取并繪制nc數(shù)據(jù)的保姆級教程
其實目前很多數(shù)據(jù)以nc格式存儲,這篇文章主要給大家介紹了關于python讀取并繪制nc數(shù)據(jù)的保姆級教程,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-05-05

