2016-06-30 107 views
2

我想驗證下載文件的簽名和證書使用pyopenssl,但文檔不清楚,谷歌沒有幫助。Pyopenssl驗證文件簽名

我在用戶的機器上有一個根CA證書,現在當用戶下載文件時,我會發送證書和簽名。首先,我需要的機器上根CA驗證證書,然後我需要的文件

驗證簽名OpenSSL中我可以使用下面的驗證CA證書

openssl verify -CAfile <root_pem> <cert_pem> 

並按照驗證文件

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

我在找等同方式使用Python做到這一點,最好pyopenssl

回答

7

我還在學習有關的OpenSSL一般,讓ALO ne PyOpenSSL。話雖如此,我能夠驗證文件(你的第二個指令)在PyOpenSSL下列要求:

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') 

verify()功能將在事件中返回None即驗證成功(即它什麼都不做),或者如果出現問題會引發異常。