欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-03-19 13:18:40
...

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

实例: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()
相关标签: Python python