Python ECDSA相同的公钥(使用ecdsa.VerifyingKey生成)未验证

时间:2019-05-06 23:30:32

标签: python cryptography ecdsa

如果我直接使用sk.get_verifying_key()签名密钥来生成公钥

它可以正常工作并进行验证,但是如果出于某种原因我尝试使用ecdsa.VerifyingKey.from_string手动创建公钥,它将无法验证并返回false。

复制粘贴以下代码并运行,您将观察到奇怪的差异

import random
import string
import sys
import ecdsa
import hashlib
import binascii

# randomly generate secret and public keys
sk = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p, hashfunc = hashlib.sha256)
pk = sk.get_verifying_key()

publicKeyVerifyObject = ecdsa.VerifyingKey.from_string(bytes.fromhex(binascii.hexlify(pk.to_string()).decode('utf-8')), curve=ecdsa.NIST256p)

print("public key:", binascii.hexlify(pk.to_string()))
print("public key:", binascii.hexlify(publicKeyVerifyObject.to_string()))

# a message to sign
name = "lastpeony"

# signature of the message
signature = sk.sign(name.encode('utf-8'))


#first test
try:
    print (publicKeyVerifyObject.verify(signature, name.encode('utf-8')))
except ecdsa.BadSignatureError:
    print (False) 


#second test
try:
    print (pk.verify(signature, name.encode('utf-8')))
except ecdsa.BadSignatureError:
    print (False) 

我期望这是两个测试的True输出。

1 个答案:

答案 0 :(得分:2)

您在hashfunc = hashlib.sha256中缺少publicKeyVerifyObject,默认值为sha1

尝试

publicKeyVerifyObject = ecdsa.VerifyingKey.from_string(bytes.fromhex(binascii.hexlify(pk.to_string()).decode('utf-8')), curve=ecdsa.NIST256p, hashfunc = hashlib.sha256)

结果:

public key: b'659ee7dcc3905b7be2969ec1c09824d81d85f54202865eeee3e5a950f585d092b90727759bded7caad24825a501e6e4bf2cb05726d9a153de7a3cc3a58ccc7c7'
public key: b'659ee7dcc3905b7be2969ec1c09824d81d85f54202865eeee3e5a950f585d092b90727759bded7caad24825a501e6e4bf2cb05726d9a153de7a3cc3a58ccc7c7'
True
True