pyopenssl

Posted baird

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pyopenssl相关的知识,希望对你有一定的参考价值。

官方文档:https://pyopenssl.org/en/stable/

签名示例:

 1 def MakeSign(message):
 2     sorted_message = sorted(message)  # 排序
 3     sign_message = ""
 4     for key in sorted_message:  # 拼接
 5         if sign_message == "":
 6             sign_message = sign_message + key + "=" + str(message[key])
 7         else:
 8             sign_message = sign_message + "&" + key + "=" + str(message[key])
 9     print("待签名的串:==>",sign_message)
10 
11     # with open(‘pri2.key‘, ‘r‘) as f:  # 获取私匙
12     #     privkey = rsa.PrivateKey.load_pkcs1(f.read().encode())
13     #
14     # sign_pre = rsa.sign(sign_message.encode(), privkey, ‘SHA-256‘)  # 签名
15     # sign = base64.b64encode(sign_pre)  # base64编码
16 
17     import OpenSSL
18     from OpenSSL._util import lib as _lib
19     FILETYPE_PEM = _lib.SSL_FILETYPE_PEM
20 
21     with open(pri3.key, rb) as f:  # 获取私匙
22         pkey = OpenSSL.crypto.load_privatekey(FILETYPE_PEM, buffer=f.read())
23 
24     sign = OpenSSL.crypto.sign(pkey,sign_message, "sha256")
25     sign = base64.b64encode(sign)  # base64编码
26     print("签名结果:==>",sign)
27     return sign

 

验签示例:(验证成功返回None,否则返回错误信息)

 1 def MakeVerify(sign,message):
 2     sign = base64.b64decode(sign)
 3     print("base64解码后的签名==》",sign)
 4     with open(pub.key, rb) as f:  # 获取私匙
 5         pubkey = OpenSSL.crypto.load_publickey(FILETYPE_PEM,buffer=f.read())
 6     x509 = OpenSSL.crypto.X509()
 7     x509.set_pubkey(pubkey)
 8     a = OpenSSL.crypto.verify(x509, sign, message, sha256)
 9     print(a)
10 MakeVerify(sign,message)

以上是关于pyopenssl的主要内容,如果未能解决你的问题,请参考以下文章

Python:使用 pyOpenSSL.crypto 读取 pkcs12 证书

让 pyOpenSSL 客户端使用 SSL 会话恢复

为啥 pyOpenSSL 中没有定义 context.set_tmp_ecdh()?

如何在 Windows 7 64 位上安装 PyOpenSSL?

使用 pyOpenSSL 从证书或其他连接信息中提取公钥

PyopenSSL和scrapy安装在Python 27,Win 64 Bit中失败