图普公钥见tupu_public_key
import time
import random
import base64
import rsa
def sign(secret_id, timestamp, nonce, private_key):
"""get the signature"""
sign_string = "%s,%s,%s" % (secret_id, timestamp, nonce)
signature = base64.b64encode(
rsa.sign(sign_string.encode("utf-8"), rsa.PrivateKey.load_pkcs1(private_key), 'SHA-256')).decode('utf-8')
return signature
def verify(signature, verify_string, public_key):
"""verify the signature"""
try:
rsa.verify(verify_string.encode("utf-8"),
base64.b64decode(signature), rsa.PublicKey.load_pkcs1_openssl_pem(public_key))
return "Success"
except rsa.pkcs1.VerificationError:
print("Verification Failed")
return "Failed"
def getKeyByFile(filename):
f = open(filename)
lines = f.read()
f.close()
return lines
def test_sign():
secret_id = "your_secret_id" # your secret id
private_key = getKeyByFile("my_private_key.pem") # your private key
timestamp = str(time.time())
nonce = str(random.random())
signature = sign(secret_id, timestamp, nonce, private_key)
print(signature)
def test_verify():
try:
import mock_tupu_service
mockResponse = mock_tupu_service.mock_service()
except:
mockResponse = {
"json": "{\"5c8213b9bc807806aab0a574\":{\"speechs\":[{\"name\":\"13.mp3\",\"label\":1,\"review\":false,\"details\":[{\"startTime\":5,\"endTime\":10,\"label\":1,\"rate\":0.9640088528394699},{\"startTime\":35,\"endTime\":40,\"label\":1,\"rate\":0.7449841499328613}]},{\"name\":\"za8gq-zb1kt.wma\",\"label\":0,\"review\":false,\"details\":[]}]},\"code\":0,\"message\":\"success\",\"nonce\":\"0.01627771095362096\",\"timestamp\":1552391372490}",
"signature": "signature_from_tupu_service"
}
public_key = getKeyByFile("tupu_public_key.pem")
verification = verify(mockResponse["signature"], mockResponse["json"], public_key)
print(verification)
if __name__ == "__main__":
test_sign()
# eg: IjnFAWYB23ssf6EO+iVlTmKzim5dm6kmtZviScULWhy1YMMkCJJID18y4y4EoDiUDDd8uZoIUAVWyZThmC+i3iE/Re4hZCx2nk1BC4KYCNiHTbW3e1p21GbvfWv4lnKfEdN+A8+h/yq0+hvwVtSB/8zS7RBsyV1hAoSIAlag/7g=
test_verify()
# eg: Success or Failed