【问题标题】:Verifying signature - What is causing invalid signature?验证签名 - 导致无效签名的原因是什么?
【发布时间】:2019-01-05 05:11:09
【问题描述】:

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

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

    只需替换这个:

    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")
    

    【讨论】:

    • 好的。这样可行。但是在 .txt 文件中,我也有一些其他数据,这就是我使用 readlines () 的原因。如果是这种情况,我该如何解决?
    • 我添加了一个小文本。如果你想要 100% 的文本文件,你需要使用 base64 来存储你的签名。
    • 我使用encoded = signature.encode('base64') 进行编码,使用signature = encoded.decode('base64') 进行解码。我仍然像以前一样得到无效的签名。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多