2015-08-15 2 views
2

J'essaye de créer une signature non-détachée sur python3. J'ai actuellement du code qui le fait sur python2 avec m2crypto, mais m2crypto n'est pas disponible pour python3.Signature non-détachée PKCS # 7 SHA1 + RSA sans M2Crypto

J'ai essayé rsa, pycrypto et openssl, mais je n'ai pas vu comment.

est ici la commande OpenSSL équivalente:

openssl smime -sign -signer $CRTFILE -inkey $KEYFILE -outformDER -nodetach 

Il est l'option nodetach que je ne peux pas imiter soit rsa, pyopenssl ou pycrypto.

Est-ce que quelqu'un le fait sur python3? J'aimerais éviter d'utiliser Popen + openssl autant que possible.

Répondre

0

J'ai fini par résoudre ce avec OpenSSL.crypto, mais, avec quelques méthodes internes:

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