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()
上一篇: 访问域名时直接访问默认的工程,执行默认的方法—备忘录《二》
下一篇: MD5(MD5 消息摘要算法)