Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

python - Pyopenssl to verify the file signature

I want to verify the downloaded file's signature and cert using pyopenssl, but the documentation is not clear and Google is of no help.

I have a root CA cert in user's machine, now when user download the file then I will send a certificate and signature along with it. First I need to verify the certificate with rootCA on machine then I need to verify the signature with file

In openssl I can use following to verify the ca cert

openssl verify -CAfile <root_pem> <cert_pem>

and following to verify the file

openssl dgst <algo> -verify <cert_pub_key> -signature <signature> <file>

I am looking for equivalent way to do it using python, most preferably pyopenssl

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm still learning about OpenSSL in general, let alone PyOpenSSL. Having said that, I was able to verify a file (your second command) in PyOpenSSL with the following:

from OpenSSL.crypto import load_publickey, FILETYPE_PEM, verify, X509

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

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

with open(public_key_filename) as f:
    public_key_data = f.read()

# load in the publickey file, in my case, I had a .pem file.
# If the file starts with
#     "-----BEGIN PUBLIC KEY-----"
# then it is of the PEM type. The only other FILETYPE is
# "FILETYPE_ASN1".
pkey = load_publickey(FILETYPE_PEM, public_key_data)

# the verify() function expects that the public key is
# wrapped in an X.509 certificate
x509 = X509()
x509.set_pubkey(pkey)

# perform the actual verification. We need the X509 object,
# the signature to verify, the file to verify, and the
# algorithm used when signing.
verify(x509, signature, file_data, 'sha256')

The verify() function will return None in the event that verification is successful (i.e. it does nothing) or it will raise an Exception if something went wrong.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...