首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从p7s文件中提取签名?

如何从p7s文件中提取签名?
EN

Stack Overflow用户
提问于 2022-07-13 17:29:02
回答 1查看 218关注 0票数 0

我需要Python代码从p7s文件中提取由对文档进行数字签名所产生的签名,在这两种情况下,有效负载都在p7s文件的内部和外部。我尝试过几个密码包(PyOpenSSL、PyCripto、密码学、ASN1Crypto和其他几个),但都没有用。我基本上能够提取其他一切(证书、有效载荷、签名时间戳等),但不能提取加密摘要(签名)。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-23 00:07:47

代码语言:javascript
复制
# Python 3.10 code to extract relevant data from a PKCS#7 signature file

from datetime import datetime
from asn1crypto import cms
from cryptography import x509
from cryptography.hazmat.primitives.serialization import pkcs7

# these are the components we are going to extract
payload: bytes                      # the original payload
signature: bytes                    # the digital signature
signature_algorithm: str            # the algorithm used to generate the signature
signature_timestamp: datetime       # the signature's timestamp
payload_hash: bytes                 # the payload hash
hash_algorithm: str                 # the algorithm used to calculate the payload hash
cert_chain: list[x509.Certificate]  # the X509 certificate chain

# define the PKCS#7 signature file path here
p7s_filepath: str = 'my_signature_file_path.p7s'

# load the p7s file
with open(p7s_filepath, 'rb') as f:
    p7s_bytes: bytes = f.read()
    f.close()

# extract the certificater chain
cert_chain = pkcs7.load_der_pkcs7_certificates(p7s_bytes)

# extract the needed structures
content_info: cms.ContentInfo = cms.ContentInfo.load(p7s_bytes)
signed_data: cms.SignedData = content_info['content']
signer_info: cms.SignerInfo = signed_data['signer_infos'][0]

# extract the payload (None if payload is detached)
payload = signed_data['encap_content_info']['content'].native

# extract the remaining components
signature = signer_info['signature'].native
signature_algorithm = signer_info['signature_algorithm']['algorithm'].native
hash_algoritmo = signer_info['digest_algorithm']['algorithm'].native

signed_attrs = signer_info['signed_attrs']
for signed_attr in signed_attrs:
    match signed_attr['type'].native:
        case 'message_digest':
            payload_hash = signed_attr['values'][0].native
        case 'signing_time':
            signature_timestamp = signed_attr['values'][0].native
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72970360

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档