+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2020-04(16)

2020-05(28)

2020-06(48)

2020-07(29)

2020-08(42)

python生成数字签名及验证签名

发布于2021-04-03 20:16     阅读(2268)     评论(0)     点赞(24)     收藏(5)


0

1

2

3

4

5

6

7

8

公私钥生成方法,请见前文

实例:python生成数字签名及验证

import base64

from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15

# 签名消息
message = "action=xx&contract_no=xx&offer_id=xx&product_id=xx&OjJNgXdJxAVDeSNEUhi4ANNCQmtYHFN1"


def ras_en(privateKey_file):
    """使用私钥生成数字签名"""
    with open(privateKey_file, 'r') as f:
        h = SHA256.new(message.encode("utf-8"))
        print(h.hexdigest())

        key = RSA.importKey(f.read())
        signer = pkcs1_15.new(key).sign(h)
        signature = base64.b64encode(signer)

        print(signature.decode('utf-8'))
        return signature


def verify_key(publicKey_file, signature):
    """使用公钥验证数字签名"""
    with open(publicKey_file, 'r') as f:
        h = SHA256.new(message.encode("utf-8"))
        key = RSA.importKey(f.read())
        try:
            pkcs1_15.new(key).verify(h, base64.b64decode(signature))
            print("The signature is valid.")
        except (ValueError, TypeError):
            print("The signature is not valid.")


def main():
    private_file = 'private.rsa'
    public_file = 'public.rsa'

    signature = ras_en(private_file)
    verify_key(public_file, signature)


if __name__ == '__main__':
    main()

0

1

2

3

4

5



所属网站分类: 技术文章 > 博客

作者:倒车请注意

链接: https://www.pythonheidong.com/blog/article/915666/9a05aeaae4e42c8ec632/

来源: python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

24 0
收藏该文
已收藏

评论内容:(最多支持255个字符)