2016-06-30 146 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即验证成功(即它什么都不做),或者如果出现问题会引发异常。