PKCS #7 detached signature with Python and PyOpenS

2019-03-22 05:49发布

问题:

I need to get a detached PKCS #7 signature of some string in Python, using PyOpenSSL. I've got a key in .p12 file.

So far, I'm trying to do so:

 from OpenSSL.crypto import load_pkcs12, sign

 pkcs12 = load_pkcs12(key_dat, key_pwd)
 algo = pkcs12.get_certificate().get_signature_algorithm()
 pkey = pkcs12.get_privatekey()
 sg = sign(pkey, manifest, algo)

But it's not what required.

I've searched net, but most examples are related to signing email chunks and use M2Crypto. Is there any way of doing it in bare PyOpenSSL?

回答1:

The PKCS#7 OpenSSL functions that you need for this do not seem to be exported by the Python OpenSSL wrapper. You could try to do this via the internals of the crypto module, for example like the following snippet:

>>> with open('cleg.p12', 'r') as f:
...   p12data=f.read()
>>> p12=crypto.load_pkcs12(p12data,'passphrase')
>>> signcert=p12.get_certificate()
>>> pkey=p12.get_privatekey()
>>> bio_in=crypto._new_mem_buf(manifest)
>>> PKCS7_DETACHED=0x40
>>> pkcs7=crypto._lib.PKCS7_sign(signcert._x509, pkey._pkey, crypto._ffi.NULL, bio_in, PKCS7_DETACHED)
>>> bio_out=crypto._new_mem_buf()
>>> crypto._lib.i2d_PKCS7_bio(bio_out, pkcs7)
1
>>> sigbytes=crypto._bio_to_string(bio_out)

After this, sigbytes contains the signature, ASN.1 DER encoded. The constant value for PKCS7_DETACHED is defined in the pkcs7.h header file in OpenSSL.

As you probably know, any identifiers that start with _ are internal to the crypto module and are not supposed to be used by you directly. Therefore, this answer is just for illustration purposes. A proper solution (with correct memory management) should be added to the crypto module itself.