代码之家  ›  专栏  ›  技术社区  ›  Utkonos

使用Python从PE文件中提取软件签名证书

  •  0
  • Utkonos  · 技术社区  · 7 年前

    尝试使用从PE文件中提取证书时 cryptography ,它失败了 ValueError: Unable to load certificate .我可以使用 subprocess 还有 openssl 命令行。我想了解使用的代码版本中出现了什么问题 密码学 .

    我使用的是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:无法加载证书

    0 回复  |  直到 7 年前
        1
  •  2
  •   staticmax    6 年前

    问题是签名是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)