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

时间:2018-07-28 06:37:02

标签: python-2.7 rsa verification public-key dsa

我需要使用RSA公钥和私钥对消息进行签名和验证。接收方的if verifier.verify(h,签名)部分每次都会返回“签名不真实”错误。即使一切正确。我究竟做错了什么?造成此问题的最可能原因是什么?

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

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的新手。任何帮助将不胜感激。谢谢

1 个答案:

答案 0 :(得分:0)

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

在接收器上,您从文件中读取签名,因为它是文本,然后采用第一行。

只需替换一下:

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

作者

signature=f.read()

如果要坚持使用“文本”模式,则需要在base64中对签名进行编码,然后将其写入文件,在接收方,读取第一行,并对base64进行解码。为此:

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

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

和接收者:

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