无 M2Crypto 的非分离 PKCS#7 SHA1+RSA 签名 [英] Non-detached PKCS#7 SHA1+RSA signature without M2Crypto
问题描述
我正在尝试在 python3 上创建一个非分离的签名.我目前有使用 m2crypto 在 python2 上执行此操作的代码,但 m2crypto 不适用于 python3.
I'm trying to create a non-detached signature on python3. I currently have code that does this on python2 with m2crypto, but m2crypto isn't available for python3.
我一直在尝试 rsa、pycrypto 和 openssl,但还没有找到方法.
I've been trying rsa, pycrypto and openssl, but haven't seen to find how.
这是等效的 OpenSSL 命令:
Here's the equivalent OpenSSL command:
openssl smime -sign -signer $CRTFILE -inkey $KEYFILE -outformDER -nodetach
这是我无法用 模仿的 nodetach
选项rsa、pyopenssl 或 pycrypto.
It's the nodetach
option that I can't imitate with either rsa, pyopenssl or pycrypto.
有人在python3上做过这个吗?我想尽可能避免使用 Popen+openssl.
Has anyone does this on python3? I'd like to avoid using Popen+openssl as much as possible.
推荐答案
我实际上最终使用 OpenSSL.crypto
解决了这个问题,尽管使用了一些内部方法:
I actually ended up solving this with OpenSSL.crypto
, albeit, with some internal methods:
from OpenSSL import crypto
PKCS7_NOSIGS = 0x4 # defined in pkcs7.h
def create_embeded_pkcs7_signature(data, cert, key):
"""
Creates an embeded ("nodetached") pkcs7 signature.
This is equivalent to the output of::
openssl smime -sign -signer cert -inkey key -outform DER -nodetach < data
:type data: bytes
:type cert: str
:type key: str
""" # noqa: E501
assert isinstance(data, bytes)
assert isinstance(cert, str)
try:
pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key)
signcert = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
except crypto.Error as e:
raise ValueError('Certificates files are invalid') from e
bio_in = crypto._new_mem_buf(data)
pkcs7 = crypto._lib.PKCS7_sign(
signcert._x509, pkey._pkey, crypto._ffi.NULL, bio_in, PKCS7_NOSIGS
)
bio_out = crypto._new_mem_buf()
crypto._lib.i2d_PKCS7_bio(bio_out, pkcs7)
signed_data = crypto._bio_to_string(bio_out)
return signed_data
这篇关于无 M2Crypto 的非分离 PKCS#7 SHA1+RSA 签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!