我目前正在開發一個使用 PyCryptodome 在 python 中自動解密的小程式
我有一個 shell 版本的測驗,它作業得很好,但我不明白為什么它不能在 python 中驗證(也許是編碼/解碼問題?)
私人 ECC 密鑰生成:
openssl ecparam -name prime256v1 -genkey -noout -out key.pem
公鑰生成:
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
蟒蛇版本:
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
uj5u.com熱心網友回復:
data 不是 base64 編碼的,但您正在嘗試在計算哈希之前對其進行解碼。
還要echo在輸出中添加一個 '\n'(try 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.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/359455.html
