PKCS #7 detached signature with Python and PyOpenSSL

前端 未结 1 768
独厮守ぢ
独厮守ぢ 2021-02-11 05:26

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:



        
1条回答
  •  你的背包
    2021-02-11 05:46

    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.

    0 讨论(0)
提交回复
热议问题