[英]Extract Software Signing Cert using Python from a PE File
嘗試使用cryptography
從 PE 文件中提取證書時,失敗並顯示ValueError: Unable to load certificate
。 我能夠使用subprocess
和openssl
命令行從同一個 PE 文件中正確提取證書。 我想了解使用cryptography
的代碼版本出了什么問題。
我正在使用 Python 3.7.1、密碼學 2.4.2 和 pefile 2018.8.8
import pefile
from cryptography import x509
from cryptography.hazmat.backends import default_backend
pe = pefile.PE(fname)
pe.parse_data_directories(directories=[pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_SECURITY']])
sigoff = 0
siglen = 0
for s in pe.__structures__:
if s.name == 'IMAGE_DIRECTORY_ENTRY_SECURITY':
sigoff = s.VirtualAddress
siglen = s.Size
pe.close()
with open(fname, 'rb') as fh:
fh.seek(sigoff)
thesig = fh.read(siglen)
cert = x509.load_der_x509_certificate(thesig[8:], default_backend())
這失敗並出現ValueError: Unable to load certificate
問題是簽名是 PKCS7 對象。 MS 已將其記錄在Word中。 我還沒有找到PDF版本...
所以需要先解析PKCS7對象。 我為此使用asn1crypto 。
這對我有用:
import pefile
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from asn1crypto import cms
pe = pefile.PE(fname)
sigoff = pe.OPTIONAL_HEADER.DATA_DIRECTORY[pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_SECURITY"]].VirtualAddress
siglen = pe.OPTIONAL_HEADER.DATA_DIRECTORY[pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_SECURITY"]].Size
pe.close()
with open(fname, 'rb') as fh:
fh.seek(sigoff)
thesig = fh.read(siglen)
signature = cms.ContentInfo.load(thesig[8:])
for cert in signature["content"]["certificates"]:
parsed_cert = x509.load_der_x509_certificate(cert.dump(), default_backend())
print(parsed_cert)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.