SoFunction
Updated on 2024-11-10

Python3.7 hashlib and Crypto based on the implementation of the addition of signature verification function (example code)

Environment:

Python3.7

Dependency Library:

import datetime
import random
import requests
import hashlib
import json
import base64
from  import RSA
from  import PKCS1_v1_5
from  import SHA256
from  import AES

Extra signatures:

def sign(signflag,keypath,baseRequest):
 #http request body
  print(baseRequest)
  # countersigning signs
  if not signflag: return baseRequest
  else:
   # Fetch business data from the request body
    businessdata = (baseRequest["data"])
    # Read private key (.key format, can use openssl or generate)
    with open(keypath,'r') as rsaKeyFile:
      rsaKey = ().replace("\n",'')
      print(rsaKey)
    rsaKeyBytes = base64.b64decode(rsaKey)
    print(rsaKeyBytes)
    #SHA256 digest, RSA encryption
    priKey = (rsaKeyBytes)
    signer = PKCS1_v1_5.new(priKey)
    hash_obj = (business_data.encode('utf-8'))
    signature = base64.b64encode((hash_obj))
    print(signature)
    # Add the signature to the request body and return
    baseRequest['sign'] = ()
    print(baseRequest)
    return baseRequest

Check the signatures:

def validata(signflag,cerpath,res):
  if not signflag: return res
  else:
   # Fetch business data and signatures
    data = res['data']
    sign = res['sign']
    # here cer has been converted to pem format, use openssl tool
    #openssl x509 -inform der -pubkey -noout -in >
    cert = open(cerpath).read().replace("-----BEGIN PUBLIC KEY-----\n","").replace("-----END PUBLIC KEY-----\n","").replace("\n","")
    print(cert)
 # Signature checking logic is the same as countersigning
    pubBytes = base64.b64decode(cert)
    pubKey = (pubBytes)
    signer = ((data).encode("utf-8"))
    verifier = PKCS1_v1_5.new(pubKey)
    return (signer,base64.b64decode(sign))

summarize

The above is a small introduction to the Python3.7 based on hashlib and Crypto to achieve the addition of the signature verification function, I hope to help you, if you have any questions please leave me a message, I will reply to you in a timely manner. I would also like to thank you very much for your support of my website!
If you find this article helpful, please feel free to reprint it, and please note the source, thank you!