Python3.7基於hashlib和Crypto實現加簽驗籤功能(例項程式碼)
阿新 • • 發佈:2020-01-09
環境:
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: #取請求體中的業務資料 businessdata = json.dumps(baseRequest["data"]) #讀取私鑰(.key格式,可使用openssl或java.keytools產生) 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: #取業務資料和簽名 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實現加簽驗籤功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對我們網站的支援!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!