验证签名 - 是什么导致无效签名?

Verifying signature - What is causing invalid signature?

我需要使用 RSA public 和私钥对消息进行签名和验证。接收方的 if verifier.verify(h, signature) 部分,每次 returns "Signature not authentic" 错误。尽管一切都是正确的。我究竟做错了什么?此问题最可能的原因是什么?

我使用以下代码生成了密钥

from Crypto.Signature import PKCS1_v1_5
from Crypto.PublicKey import RSA
key = RSA.generate(1024)
private_key=key.exportKey()
public_key=key.publickey().exportKey()

在发件人处,

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

private_key="""Private key here
-----END RSA PRIVATE KEY-----"""
message = 'To be signed'
priv_key = RSA.importKey(private_key)
h = SHA256.new(message)
signature = PKCS1_v1_5.new(priv_key).sign(h)
f=open('sign.txt','w')
f.write(signature)

在接收端,

from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from base64 import b64decode


public_key="""public key here"""
pub_key = RSA.importKey(public_key)

message = 'To be signed'
f=open('sign.txt')
sig=f.readlines()
signature=sig[0]
h = SHA256.new(message)
verifier = PKCS1_v1_5.new(pub_key)
if verifier.verify(h, signature):
   print "The signature is authentic."
else:
   print "The signature is not authentic."

我是 python 的新手。任何帮助将不胜感激。谢谢

在发件人上,您获得签名并将其作为二进制文件保存到文件中

在接收器上,您从文本文件中读取签名,然后取第一行。

只需替换为:

sig=f.readlines()
signature=sig[0]

来自

signature=f.read()

如果想坚持使用"text"模式,需要将签名进行base64编码后写入文件,接收方读取第一行,进行base64解码。为此:

在发件人上,您可以设置:

f.write(signature.encode('base64').replace('\n', ''))

在接收器上:

sig=f.readlines()
signature=sig[0].decode("base64")