我们如何在python中验证openssl签名

问题描述

在linux终端上,我如下创建映像文件的哈希

openssl dgst -sha256 -binary -out hash.bin data.jpg

使用以下命令对哈希签名

openssl pkeyutl -inkey private.key -in hash.bin -out data.sig -sign

我也可以验证数字签名

openssl pkeyutl -verify -pubin -inkey public.key -in hash.bin -sigfile data.sig 

现在,我想在python终端上用python验证数字签名。

import base64
import cryptography.exceptions
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.serialization import load_pem_public_key


with open("file_to_verify",'rb') as f:
    payload_contents = f.read()

with open("public_key_filename",'rb') as f:
    public_key = load_pem_public_key(f.read(),default_backend())

with open("signature_filename",'rb') as f:
    signature = base64.b64decode(f.read())

try:
    public_key.verify(signature,payload_contents,padding.PSS(mgf = padding.MGF1(hashes.SHA256()),salt_length = padding.PSS.MAX_LENGTH),hashes.SHA256())

except cryptography.exceptions.InvalidSignature as e:
    print('ERROR: Payload and/or signature files Failed verification!')

我有两种情况

  • 使用python中的签名和公钥验证在Linux终端上创建的hash.bin。
  • 创建Linux终端中使用的data.jpg的哈希,并使用相同的签名和公钥在python中进行验证

注意:我使用下面的代码创建二进制图像数据的哈希值

def sha256(data):
    h = hashes.Hash(hashes.SHA256(),default_backend())
    h.update(data)
    return h.finalize()

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)