无法使用 PyCryptodome ECC(ASN1?)验证签名

Can't verify signature with PyCryptodome ECC (ASN1?)

我目前正在开发一个小程序,使用 PyCryptodome

在 python 中自动解密

我有一个 shell 版本的测试,工作正常,但我不明白为什么它不能在 python 中验证(可能是 encode/decode 问题? )

私有 ECC 密钥生成:

openssl ecparam -name prime256v1 -genkey -noout -out key.pem

public 密钥生成:

openssl ec -in key.pem -pubout -out publicKey.pub

要签名的数据:

echo test > i_am_a_test.txt

生成签名文件:

openssl dgst -sign key.pem -out data.sig i_am_a_test.txt

验证签名:

openssl dgst -verify publicKey.pub -signature data.sig i_am_a_test.txt
Verified OK

python版本:

import base64
from Crypto.Hash import SHA256
from Crypto.PublicKey import ECC
from Crypto.Signature import DSS

if __name__ == "__main__":
    # the pub key from publicKey.pub
    pub = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEzlNm3snsI8D4VWf7vwNkR4WG0F/ymFgew1xUIVn6tUL0ln+lc/lKxOIUa3O2uFkoCUwEALCTpasWbNUoNGi+JQ=="
    # the data to verify
    data = "test"
    # the signature from data.sig
    sig = "MEYCIQCLbTx5uk18vixVZiG/s9bpBso5u3BZcJDNDSUX5bZc6gIhAMbqzdioGmelKIgVlUmZhtaYs9Szs9asATHCJvTIx7G8"
    
    key = ECC.import_key(base64.b64decode(pub))
    h = SHA256.new(base64.b64decode(data))
    verifier = DSS.new(key, 'fips-186-3', encoding="der")
    verifier.verify(h, base64.b64decode(sig))
    print("The message is authentic.")

验证输出

Traceback (most recent call last):
  File "/home/admin/Documents/tests/main.py", line 51, in <module>
    verifier.verify(h, base64.b64decode(sig))
  File "/home/admin/.local/share/virtualenvs/admin-afIRSt_6/lib/python3.8/site-packages/Crypto/Signature/DSS.py", line 169, in verify
    raise ValueError("The signature is not authentic")
ValueError: The signature is not authentic

data 不是 base64 编码的,但您正在尝试在计算哈希值之前对其进行解码。

另外echo在输出中添加了一个'\n'(尝试xxd i_am_a_test.txt),所以数据实际上是b'test\n'.

import base64
from Crypto.Hash import SHA256
from Crypto.PublicKey import ECC
from Crypto.Signature import DSS

if __name__ == "__main__":
    # the pub key from publicKey.pub
    pub = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEzlNm3snsI8D4VWf7vwNkR4WG0F/ymFgew1xUIVn6tUL0ln+lc/lKxOIUa3O2uFkoCUwEALCTpasWbNUoNGi+JQ=="
    # the data to verify
    data = b"test\n"
    # the signature from data.sig
    sig = "MEYCIQCLbTx5uk18vixVZiG/s9bpBso5u3BZcJDNDSUX5bZc6gIhAMbqzdioGmelKIgVlUmZhtaYs9Szs9asATHCJvTIx7G8"

    key = ECC.import_key(base64.b64decode(pub))
    h = SHA256.new(data)
    verifier = DSS.new(key, 'fips-186-3', encoding="der")
    verifier.verify(h, base64.b64decode(sig))
    print("The message is authentic.")

输出:

The message is authentic.