背景:
rsa签名/验名
公钥私钥文件
公钥和私钥获取不进行细致描述,网络有较多资料,本文提供一对公钥和私钥。
需要关注的公钥和私钥的标准格式:
公钥public_key.pem
标准格式:
-----BEGIN PUBLIC KEY-----
xxxx
-----END PUBLIC KEY-----
真实数据
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDa+ty6qxDH3U82A0xKXDWz1ysM3AQXaAO8DzFeGIhQeUDJktmEk2oGM1/mEjBkfsr6XZ32FvIHAvZRnlNK8OZR9TyWFqjf8w2HopdUjSWAyGylUxHHiC5QdkxTzd+3OoQy7FrQnxdRzKZo2xclWBME7fGzYZCmb6Ws/Mp7oKVbXwIDAQAB
-----END PUBLIC KEY-----
私钥private_key.pem
标准格式:
-----BEGIN RSA PRIVATE KEY-----
xxxx
-----END RSA PRIVATE KEY-----
真实数据:
-----BEGIN RSA PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANr63LqrEMfdTzYDTEpcNbPXKwzcBBdoA7wPMV4YiFB5QMmS2YSTagYzX+YSMGR+yvpdnfYW8gcC9lGeU0rw5lH1PJYWqN/zDYeil1SNJYDIbKVTEceILlB2TFPN37c6hDLsWtCfF1HMpmjbFyVYEwTt8bNhkKZvpaz8ynugpVtfAgMBAAECgYBI2O+ZQdNhSeRSCaLVkftjio8NxhuuVbH4W+2Gag7fBpdg93NZQVkiGvEqLp7er7eCtqYX+eYmIvwihtMauS1FNOSo5ifwAFd7DPNsym7bBk/UW9f8kFg4o6rGqIqnOcdOj8Wts1bpxFBFSoNS2SUNr+WBHy9rCxZeiCg+zWMX4QJBAPhCy2ydy3wLUm4kZ4p9FjEabBL0A07BHn1ro6k9JyqS3AJD8Memsc5lo9cOcRS37bhNGwvjGh0kAmkI85PArIkCQQDhzmVAGMTxyhyKoUNQ6TcfruhN/cbBuA0IdFonA9YoPhTdT6pDLX6Vm4RIz8lGnws4tJNlGcKWi/r0/pQsJt6nAkEAhxhZ+GY5x+ulVJhs27jL7baSHxI4BpAill+PtNW5TXqTTIxKJ2r3kPhQWwPZ10trigIzeJmBqV/iC+Q6ICoV+QJAGqd6XC6QUNpCtDqE77AXya2jzlD+fS90mmLhoWlahjWN0PHuby+XmaFZ5B5i6+sqL+9g1rZLuemcHf9PDkcoUQJBAM+fvK94I05CXQXVVDsDelAwRo5BryaM1tCk0ojgfo++PXxvZc0LXO4BxNBdO1Po9vl4RGZA4m6mTMIBOzowKoU=
-----END RSA PRIVATE KEY-----
rsa签名/验名
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
import Crypto.Hash.SHA512
from Crypto.Hash import SHA
import base64
# 签名
# plaintext:string,被签名信息
# keyPath:私钥路径
# 返回:base64的签名输出
def rsa_sign(plaintext, keyPath):
# 读私钥
with open(keyPath) as f:
key = f.read()
# 实例验名对象
signer = PKCS1_v1_5.new(RSA.importKey(key))
# 将被签名信息以SHA算法进行哈希转换
hash_value = SHA.new(plaintext.encode('utf-8'))
# 签名
sign = signer.sign(hash_value)
# base64输出签名
return base64.b64encode(sign)
# 验签
# sign:签名
# plaintext:string,被签名信息
# keyPath:私钥路径
# 返回:base64的签名输出
def rsa_verify(sign, plaintext, keypath):
# 读私钥
with open(keypath) as f:
key = f.read()
# 将被签名信息以SHA算法进行哈希转换
hash_value = SHA.new(plaintext.encode('utf-8'))
# 实例验名对象
verifier = PKCS1_v1_5.new(RSA.importKey(key))
# 验证,通过返回true,失败返回false
return verifier.verify(hash_value, base64.b64decode(sign))
if __name__ == '__main__':
message = 'RSA数字签名演示'
privatekeyPath = 'private_key.pem'
signature = rsa_sign(message, privatekeyPath)
publickeyPath = 'public_key.pem'
result = rsa_verify(signature, message, publickeyPath)
print(result)
案例介绍
测试过程中,需要对参数进行rsa签名进行加密,真实测试案例如下,可供参考
- 将需要签名的参数按字⺟母
正序排列
列后得到待签名串串a=1&b=2&c=3
- ⽤用合作⽅方的私钥对待签名串串进⾏行行加密(使⽤用SHA1withRSA算法)得到加密值
kLTAWcBcUD4nv3YUzOhIhu...
值为空的参数不不需要参与签名 签名时不不要做URL Encoding,使⽤用原始值即可 - 将加密值作为
sign
的值拼接到参数后得到a=1&b=2&c=3&sign=kLTAWcBcUD4nv3YUzOhIhu... 4
. 最终请求时要对参数进⾏行行URL Encoding。
代码实现(Get请求+签名)
# -*- coding: utf-8 -*-
import time
import base64
import requests
import SignUtil
import urllib.request
url = 'url = 'https://xx.???.com/???/?/?''
parsMap = {
'partnerId': '??',
'timestamp': round(time.time() * 1000),
'tradeNo': 1552726887353,
'version': '1.0',
}
def tradeCaseGet():
pars = ''
# 字典排序后,拼接url参数
for key in sorted(parsMap):
pars += "%s=%s&" %(key, parsMap[key])
# 去掉最后一个&
pars=pars[0:-1]
print(pars)
# 调用rsa算法,算法在前面代码
sign = SignUtil.rsa_sign(pars, 'private_key.pem')
# 字典添加sign
parsMap['sign'] = sign
# 对url参数进行urlencode
str_item = urllib.parse.urlencode(parsMap)
# 发送get请求
response = requests.get(url, str_item)
# 打印返回值
print(response.text)
if __name__ == '__main__':
tradeCaseGet()
代码实现(Post请求+签名)
# -*- coding: utf-8 -*-
import time
import base64
import requests
import SignUtil
url = 'https://xx.???.com/???/?/?'
parsMap = {
'partnerId': 'xxx',
'timestamp': round(time.time() * 1000),
'goodId': 'xxx',
'amount': 1,
'totalFee': 600,
'userId': 'xxxxx',
'tradeNo': round(time.time() * 1000),
'version': '1.0'
}
def vipBuyCase():
pars = ''
# 字典排序后拼接待签名信息
for key in sorted(parsMap):
pars += "%s=%s&" % (key, parsMap[key])
print(pars)
# 去除最后一个&
pars=pars[0:-1]
# 签名,签名方法见前面
parsMap['sign'] = SignUtil.rsa_sign(pars, 'private_key.pem')
print(parsMap)
# 发送post请求
response = requests.post(url, parsMap)
# 打印返回结果
print(response.text)
if __name__ == '__main__':
vipBuyCase()