Пример #1
0
    def _encrypt(self):
        """Use your key thing to encrypt things."""
        from M2Crypto import BIO, SMIME, X509
        CERT = self.settings.private_cert
        PUB_CERT = self.settings.public_cert
        PAYPAL_CERT = self.settings.paypal_cert
        CERT_ID = self.settings.cert_id

        # Iterate through the fields and pull out the ones that have a value.
        plaintext = 'cert_id=%s' % CERT_ID
        for name, value in self.items.iteritems():
            plaintext += '\n%s=%s' % (name, value)
        #plaintext = plaintext.encode('utf-8')

        # Begin crypto weirdness.
        s = SMIME.SMIME()    
        s.load_key_bio(BIO.openfile(CERT), BIO.openfile(PUB_CERT))
        p7 = s.sign(BIO.MemoryBuffer(plaintext), flags=SMIME.PKCS7_BINARY)
        x509 = X509.load_cert_bio(BIO.openfile(PAYPAL_CERT))
        sk = X509.X509_Stack()
        sk.push(x509)
        s.set_x509_stack(sk)
        s.set_cipher(SMIME.Cipher('des_ede3_cbc'))
        tmp = BIO.MemoryBuffer()
        p7.write_der(tmp)
        p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY)
        out = BIO.MemoryBuffer()
        p7.write(out)
        return out.read()
Пример #2
0
    def _encrypt(self):
        """Use your key thing to encrypt things."""
        from M2Crypto import BIO, SMIME, X509

        # Iterate through the fields and pull out the ones that have a value.
        plaintext = 'cert_id=%s\n' % self.cert_id
        for name, field in self.fields.items():
            value = None
            if name in self.initial:
                value = self.initial[name]
            elif field.initial is not None:
                value = field.initial
            if value is not None:
                # @@@ Make this less hackish and put it in the widget.
                if name == "return_url":
                    name = "return"
                plaintext += u'%s=%s\n' % (name, value)
        plaintext = plaintext.encode('utf-8')

        # Begin crypto weirdness.
        s = SMIME.SMIME()
        s.load_key_bio(BIO.openfile(self.private_cert), BIO.openfile(self.public_cert))
        p7 = s.sign(BIO.MemoryBuffer(plaintext), flags=SMIME.PKCS7_BINARY)
        x509 = X509.load_cert_bio(BIO.openfile(self.paypal_cert))
        sk = X509.X509_Stack()
        sk.push(x509)
        s.set_x509_stack(sk)
        s.set_cipher(SMIME.Cipher('des_ede3_cbc'))
        tmp = BIO.MemoryBuffer()
        p7.write_der(tmp)
        p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY)
        out = BIO.MemoryBuffer()
        p7.write(out)
        return out.read()
Пример #3
0
def create_signature_block(openssl_digest, certificate, private_key, data):
    """Produces a signature block for the data.

    Reference
    ---------
    http://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html#Digital_Signatures

    Note: Oracle does not specify the content of the "signature
    file block", friendly saying that "These are binary files
    not intended to be interpreted by humans".

    :param openssl_digest: alrogithm known to OpenSSL used to digest the data
    :type openssl_digest: str
    TODO: it is not used. M2Crypto cannot pass the signing digest.
    :param certificate: filename of the certificate file (PEM format)
    :type certificate: str
    :param private_key:filename of private key used to sign (PEM format)
    :type private_key: str
    :param data: the content to be signed
    :type data: str
    :returns: content of the signature block file as produced by jarsigner
    :rtype: str
    """

    smime = SMIME.SMIME()
    smime.load_key_bio(BIO.openfile(private_key), BIO.openfile(certificate))
    pkcs7 = smime.sign(BIO.MemoryBuffer(data), flags=SMIME.PKCS7_BINARY)
    tmp = BIO.MemoryBuffer()
    pkcs7.write_der(tmp)
    return tmp.read()
Пример #4
0
 def test_load_bio(self):
     bio = BIO.openfile('tests/x509.pem')
     bio2 = BIO.openfile('tests/x509.der')
     x509 = X509.load_cert_bio(bio)
     x5092 = X509.load_cert_bio(bio2, format=X509.FORMAT_DER)
     assert x509.as_text() == x5092.as_text()
     assert x509.as_pem() == x5092.as_pem()
     assert x509.as_der() == x5092.as_der()
     return
Пример #5
0
    def test_load_bio(self):
        with BIO.openfile('tests/x509.pem') as bio:
            with BIO.openfile('tests/x509.der') as bio2:
                x509 = X509.load_cert_bio(bio)
                x5092 = X509.load_cert_bio(bio2, format=X509.FORMAT_DER)

        with self.assertRaises(ValueError):
            X509.load_cert_bio(bio2, format=45678)

        self.assertEqual(x509.as_text(), x5092.as_text())
        self.assertEqual(x509.as_pem(), x5092.as_pem())
        self.assertEqual(x509.as_der(), x5092.as_der())
Пример #6
0
    def test_load_bio(self):
        bio = BIO.openfile('tests/x509.pem')
        bio2 = BIO.openfile('tests/x509.der')
        x509 = X509.load_cert_bio(bio)
        x5092 = X509.load_cert_bio(bio2, format=X509.FORMAT_DER)
        
        self.assertRaises(ValueError, X509.load_cert_bio, bio2, format=45678)

        assert x509.as_text() == x5092.as_text()
        assert x509.as_pem() == x5092.as_pem()
        assert x509.as_der() == x5092.as_der()
        return
Пример #7
0
    def form_encrypted(self, data):
        """Return an s/mime encrypted form.  Refer to 
        http://sandbox.rulemaker.net/ngps/m2/howto.smime.html for instructions."""
        from M2Crypto import BIO, SMIME, X509
        certid = self.settings["PUBLIC_CERT_ID"]
        ret = ['CERT_ID=%s' % certid]
        ret.extend([u'%s=%s' % (key, val) for key, val in data.items() if val])
        raw = "\n".join(ret)
        raw = raw.encode('utf-8')
        
        self.log_extra('Plaintext form: %s', raw)
        
        # encrypt the plaintext
        
        # make an smime object
        s = SMIME.SMIME()
        
        # load our public and private keys	
        s.load_key_bio(BIO.openfile(self.localprikey), BIO.openfile(self.localpubkey))
        
        # put the data in the buffer
        buf = BIO.MemoryBuffer(raw)
        
        # sign the text
        p7 = s.sign(buf, flags=SMIME.PKCS7_BINARY)
        
        # Load target cert to encrypt to.
        x509 = X509.load_cert_bio(BIO.openfile(self.paypalpubkey))
        sk = X509.X509_Stack()
        sk.push(x509)
        s.set_x509_stack(sk)
        
        # Set cipher: 3-key triple-DES in CBC mode.
        s.set_cipher(SMIME.Cipher('des_ede3_cbc'))
        
        # save data to buffer
        tmp = BIO.MemoryBuffer()
        p7.write_der(tmp)
        
        # encrypt
        p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY)
        out = BIO.MemoryBuffer()
        
        # write into a new buffer
        p7.write(out)
        
        # read the result
        form = out.read()
        self.log_extra('Encrypted form: %s', form)
        return mark_safe(u"""<input type="hidden" name="cmd" value="_s-xclick" />
<input type="hidden" name="encrypted" value="%s" />
        """ % form)
Пример #8
0
    def setUp(self):
        s = SMIME.SMIME()
        s.load_key('tests/signer_key.pem', 'tests/signer.pem')
        p7 = s.sign(BIO.MemoryBuffer('some text'))
        self.filename = 'tests/sig.p7'
        f = BIO.openfile(self.filename, 'wb')
        assert p7.write(f) == 1
        f.close()

        self.filenameSmime = 'tests/sig.p7s'
        f = BIO.openfile(self.filenameSmime, 'wb')
        assert s.write(f, p7, BIO.MemoryBuffer('some text')) == 1
        f.close()
Пример #9
0
    def setUp(self):
        s = SMIME.SMIME()
        s.load_key('tests/signer_key.pem', 'tests/signer.pem')
        p7 = s.sign(BIO.MemoryBuffer('some text'))
        self.filename = 'tests/sig.p7'
        f = BIO.openfile(self.filename, 'wb')
        self.assertEqual(p7.write(f), 1)
        f.close()

        p7 = s.sign(BIO.MemoryBuffer('some text'), SMIME.PKCS7_DETACHED)
        self.filenameSmime = 'tests/sig.p7s'
        f = BIO.openfile(self.filenameSmime, 'wb')
        self.assertEqual(s.write(f, p7, BIO.MemoryBuffer('some text')), 1)
        f.close()
Пример #10
0
    def setUp(self):
        s = SMIME.SMIME()
        s.load_key("tests/signer_key.pem", "tests/signer.pem")
        p7 = s.sign(BIO.MemoryBuffer("some text"))
        self.filename = "tests/sig.p7"
        f = BIO.openfile(self.filename, "wb")
        assert p7.write(f) == 1
        f.close()

        p7 = s.sign(BIO.MemoryBuffer("some text"), SMIME.PKCS7_DETACHED)
        self.filenameSmime = "tests/sig.p7s"
        f = BIO.openfile(self.filenameSmime, "wb")
        assert s.write(f, p7, BIO.MemoryBuffer("some text")) == 1
        f.close()
Пример #11
0
    def setUp(self):
        s = SMIME.SMIME()
        s.load_key('tests/signer_key.pem', 'tests/signer.pem')
        p7 = s.sign(BIO.MemoryBuffer(b'some text'))
        self.filename = 'tests/sig.p7'
        with BIO.openfile(self.filename, 'wb') as f:
            self.assertEqual(p7.write(f), 1)
        self.filename_der = 'tests/sig.p7.der'
        with BIO.openfile(self.filename_der, 'wb') as f:
            self.assertEqual(p7.write_der(f), 1)

        p7 = s.sign(BIO.MemoryBuffer(b'some text'), SMIME.PKCS7_DETACHED)
        self.filenameSmime = 'tests/sig.p7s'
        with BIO.openfile(self.filenameSmime, 'wb') as f:
            self.assertEqual(s.write(f, p7, BIO.MemoryBuffer(b'some text')), 1)
Пример #12
0
def load_session(pemfile):
    f = BIO.openfile(pemfile)
    cptr = m2.ssl_session_read_pem(f.bio_ptr())
    f.close()
    if cptr is None:
        raise Err.get_error()
    return Session(cptr, 1)
Пример #13
0
def load_session(pemfile):
    # type: (AnyStr) -> Session
    with BIO.openfile(pemfile) as f:
        cptr = m2.ssl_session_read_pem(f.bio_ptr())
    if cptr is None:
        raise SSLError(Err.get_error())
    return Session(cptr, 1)
Пример #14
0
def load_cert(file, format=FORMAT_PEM):
    """
    Load certificate from file.

    @type file: string
    @param file: Name of file containing certificate in either DER or
                 PEM format.
    @type format: int, either FORMAT_PEM or FORMAT_DER
    @param format: Describes the format of the file to be loaded,
                   either PEM or DER.

    @rtype: M2Crypto.X509.X509
    @return: M2Crypto.X509.X509 object.
    """
    bio = BIO.openfile(file)
    if format == FORMAT_PEM:
        return load_cert_bio(bio)
    elif format == FORMAT_DER:
        cptr = m2.d2i_x509(bio._ptr())
        if cptr is None:
            raise X509Error(Err.get_error())
        return X509(cptr, _pyfree=1)
    else:
        raise ValueError(
            "Unknown format. Must be either FORMAT_DER or FORMAT_PEM")
Пример #15
0
def verify_signature_block(certificate_file, content_file, signature):
    """Verifies the 'signature' over the 'content', trusting the 'certificate'.

    :param certificate_file: the trusted certificate (PEM format)
    :type certificate_file: str
    :param content_file: The signature should match this content
    :type content_file: str
    :param signature: data (DER format) subject to check
    :type signature: str
    :return: Error message, or None if the signature validates.
    :rtype: str
    """

    sig_bio = BIO.MemoryBuffer(signature)
    pkcs7 = SMIME.PKCS7(m2.pkcs7_read_bio_der(sig_bio._ptr()), 1)
    signers_cert_stack = pkcs7.get0_signers(X509.X509_Stack())
    trusted_cert_store = X509.X509_Store()
    trusted_cert_store.load_info(certificate_file)
    smime = SMIME.SMIME()
    smime.set_x509_stack(signers_cert_stack)
    smime.set_x509_store(trusted_cert_store)
    data_bio = BIO.openfile(content_file)
    try:
        smime.verify(pkcs7, data_bio)
    except SMIME.PKCS7_Error, message:
        return "Signature verification error: %s" % message
Пример #16
0
def load_request(file, format=FORMAT_PEM):
    """
    Load certificate request from file.

    @type file: string
    @param file: Name of file containing certificate request in
                 either PEM or DER format.
    @type format: int, either FORMAT_PEM or FORMAT_DER
    @param format: Describes the format of the file to be loaded,
                   either PEM or DER.

    @rtype: M2Crypto.X509.Request
    @return: M2Crypto.X509.Request object.
    """
    f = BIO.openfile(file)
    if format == FORMAT_PEM:
        cptr = m2.x509_req_read_pem(f.bio_ptr())
    elif format == FORMAT_DER:
        cptr = m2.d2i_x509_req(f.bio_ptr())
    else:
        raise ValueError(
            "Unknown filetype. Must be either FORMAT_PEM or FORMAT_DER")
    f.close()
    if cptr is None:
        raise X509Error(Err.get_error())
    return Request(cptr, 1)
Пример #17
0
def create_signature_block(openssl_digest, certificate, private_key,
                           extra_certs, data):

    """
    Produces a signature block for the data.

    Reference
    ---------
    http://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html#Digital_Signatures

    Note: Oracle does not specify the content of the "signature
    file block", friendly saying that "These are binary files
    not intended to be interpreted by humans".

    :param openssl_digest: alrogithm known to OpenSSL used to digest the data
    :type openssl_digest: str
    :param certificate: filename of the certificate file (PEM format)
    :type certificate: str
    :param private_key:filename of private key used to sign (PEM format)
    :type private_key: str
    :param extra_certs: additional certificates to embed into the signature (PEM format)
    :type extra_certs: array of filenames
    :param data: the content to be signed
    :type data: bytes
    :returns: content of the signature block file as produced by jarsigner
    :rtype: bytes
    """  # noqa

    smime = SMIME.SMIME()
    with BIO.openfile(private_key) as k, BIO.openfile(certificate) as c:
        smime.load_key_bio(k, c)

    if extra_certs is not None:
        # Could we use just X509.new_stack_from_der() instead?
        stack = X509.X509_Stack()
        for cert in extra_certs:
            stack.push(X509.load_cert(cert))
        smime.set_x509_stack(stack)

    pkcs7 = smime.sign(BIO.MemoryBuffer(data),
                       algo=openssl_digest,
                       flags=(SMIME.PKCS7_BINARY |
                              SMIME.PKCS7_DETACHED |
                              SMIME.PKCS7_NOATTR))
    tmp = BIO.MemoryBuffer()
    pkcs7.write_der(tmp)
    return tmp.read()
Пример #18
0
 def save_pem(self, filename):
     # type: (AnyStr) -> int
     """
     :param filename: name of the file to be loaded
     :return: 1 for success or 0 for failure
     """
     with BIO.openfile(filename, 'wb') as bio:
         return m2.x509_write_pem(bio.bio_ptr(), self.x509)
Пример #19
0
def load_session(pemfile):
    f = BIO.openfile(pemfile)
    cptr = m2.ssl_session_read_pem(f.bio_ptr())
    f.close()
    if cptr is None:
        from M2Crypto.SSL import SSLError
        raise SSLError(Err.get_error())
    return Session(cptr, 1)
Пример #20
0
    def save_key_der(self, file):
        # type: (AnyStr) -> int
        """
        Save the key pair to a file in DER format.

        :param file: Filename to save key to
        """
        with BIO.openfile(file, 'wb') as bio:
            return self.save_key_der_bio(bio)
Пример #21
0
    def save_pub_key(self, file):
        # type: (AnyStr) -> int
        """
        Save the public key to a filename in PEM format.

        :param file: Name of filename to save key to.
        """
        with BIO.openfile(file, 'wb') as bio:
            return m2.ec_key_write_pubkey(self.ec, bio._ptr())
Пример #22
0
    def save_key_der(self, file):
        """
        Save the key pair to a file in DER format.

        @type file: str
        @param file: Filename to save key to
        """
        bio = BIO.openfile(file, 'wb')
        return self.save_key_der_bio(bio)
Пример #23
0
    def save_pub_key(self, file):
        """
        Save the public key to a file in PEM format.

        @type file: string
        @param file: Name of file to save key to.
        """
        bio = BIO.openfile(file, 'wb')
        return m2.ec_key_write_pubkey(self.ec, bio._ptr())
Пример #24
0
    def set_tmp_dh(self, dhpfile):
        # type: (AnyStr) -> int
        """Load ephemeral DH parameters into the context.

        @param dhpfile: Filename of the file containing the PEM-encoded
                        DH parameters.
        """
        f = BIO.openfile(dhpfile)
        dhp = m2.dh_read_parameters(f.bio_ptr())
        return m2.ssl_ctx_set_tmp_dh(self.ctx, dhp)
Пример #25
0
    def set_tmp_dh(self, dhpfile):
        """Load ephemeral DH parameters into the context.

        @param dhpfile: File object containing the PEM-encoded DH
                        parameters.
        @type dhpfile:  str
        """
        f = BIO.openfile(dhpfile)
        dhp = m2.dh_read_parameters(f.bio_ptr())
        return m2.ssl_ctx_set_tmp_dh(self.ctx, dhp)
Пример #26
0
def load_pub_key(file):
    # type: (AnyStr) -> RSA_pub
    """
    Load an RSA public key from file.

    :param file: Name of file containing RSA public key in PEM format.

    :return: M2Crypto.RSA.RSA_pub object.
    """
    with BIO.openfile(file) as bio:
        return load_pub_key_bio(bio)
Пример #27
0
def load_pub_key(file):
    # type: (AnyStr) -> EC_pub
    """
    Load an EC public key from filename.

    @param file: Name of filename containing EC public key in PEM format.

    @return: M2Crypto.EC.EC_pub object.
    """
    with BIO.openfile(file) as bio:
        return load_pub_key_bio(bio)
Пример #28
0
 def _sign_RS(self, alg, header, sbs):
     priv_key_u = self._config.get('jws.rsa_key_path', None)
     if priv_key_u is None:
         raise(JWSException("No private key found for RSA signature"))
     bio = BIO.openfile(priv_key_u)
     rsa = RSA.load_key_bio(bio)
     if not rsa.check_key():
         raise(JWSException("Invalid key specified"))
     digest = self._get_sha(alg[2:])(sbs).digest()
     signature = rsa.sign_rsassa_pss(digest)
     return '%s.%s' % (sbs, base64.urlsafe_b64encode(signature))
Пример #29
0
 def from_pem_data(cls, data=None, filename=None):
     """Alternative constructor for loading from PEM format data."""
     self = cls.__new__(cls)
     if data is not None:
         bio = BIO.MemoryBuffer(str(data))
     elif filename is not None:
         bio = BIO.openfile(filename)
     else:
         msg = "Please specify either 'data' or 'filename' argument."
         raise ValueError(msg)
     self.keyobj = self.KEY_MODULE.load_pub_key_bio(bio)
     return self
Пример #30
0
def load_pub_key(file):
    """
    Load an EC public key from file.

    @type file: string
    @param file: Name of file containing EC public key in PEM format.

    @rtype: M2Crypto.EC.EC_pub
    @return: M2Crypto.EC.EC_pub object.
    """
    bio = BIO.openfile(file)
    return load_pub_key_bio(bio)
Пример #31
0
def load_crl(file):
    # type: (AnyStr) -> CRL
    """
    Load CRL from file.

    :param file: Name of file containing CRL in PEM format.

    :return: M2Crypto.X509.CRL object.
    """
    with BIO.openfile(file) as f:
        cptr = m2.x509_crl_read_pem(f.bio_ptr())

    return CRL(cptr, 1)
Пример #32
0
    def save_pub_key(self, filename):
        # type: (AnyStr) -> int
        """
        Save the DSA public key (with parameters) to a file.

        @param filename: Save DSA public key (with parameters)
                         to this file.
        @return:         1 (true) if successful
        """
        with BIO.openfile(filename, 'wb') as bio:
            ret = self.save_pub_key_bio(bio)

        return ret
Пример #33
0
    def _encrypt(self):
        """Use your key thing to encrypt things."""
        from M2Crypto import BIO, SMIME, X509
        # @@@ Could we move this to conf.py?
        CERT = settings.PAYPAL_PRIVATE_CERT
        PUB_CERT = settings.PAYPAL_PUBLIC_CERT
        PAYPAL_CERT = settings.PAYPAL_CERT
        CERT_ID = settings.PAYPAL_CERT_ID

        # Iterate through the fields and pull out the ones that have a value.
        plaintext = 'cert_id=%s\n' % CERT_ID
        for name, field in self.fields.iteritems():
            value = None
            if name in self.initial:
                value = self.initial[name]
            elif field.initial is not None:
                value = field.initial
            if value is not None:
                # @@@ Make this less hackish and put it in the widget.
                if name == "return_url":
                    name = "return"
                plaintext += u'%s=%s\n' % (name, value)
        plaintext = plaintext.encode('utf-8')

        # Begin crypto weirdness.
        s = SMIME.SMIME()
        s.load_key_bio(BIO.openfile(CERT), BIO.openfile(PUB_CERT))
        p7 = s.sign(BIO.MemoryBuffer(plaintext), flags=SMIME.PKCS7_BINARY)
        x509 = X509.load_cert_bio(BIO.openfile(settings.PAYPAL_CERT))
        sk = X509.X509_Stack()
        sk.push(x509)
        s.set_x509_stack(sk)
        s.set_cipher(SMIME.Cipher('des_ede3_cbc'))
        tmp = BIO.MemoryBuffer()
        p7.write_der(tmp)
        p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY)
        out = BIO.MemoryBuffer()
        p7.write(out)
        return out.read()
Пример #34
0
def load_key(file, callback=util.passphrase_callback):
    # type: (AnyStr, Callable) -> EC
    """
    Factory function that instantiates a EC object.

    :param file: Names the filename that contains the PEM representation
                 of the EC key pair.

    :param callback: Python callback object that will be invoked
                     if the EC key pair is passphrase-protected.
    """
    with BIO.openfile(file) as bio:
        return load_key_bio(bio, callback)
Пример #35
0
def sign():
    print 'test sign & save...',
    buf = makebuf()
    s = SMIME.SMIME()
    s.load_key('client.pem')
    p7 = s.sign(buf, SMIME.PKCS7_DETACHED)
    out = BIO.openfile('clear.p7', 'w')
    out.write('To: [email protected]\n')
    out.write('From: [email protected]\n')
    out.write('Subject: testing\n')
    buf = makebuf()  # Recreate buf, because sign() has consumed it.
    s.write(out, p7, buf)
    out.close()

    buf = makebuf()
    p7 = s.sign(buf)
    out = BIO.openfile('opaque.p7', 'w')
    out.write('To: [email protected]\n')
    out.write('From: [email protected]\n')
    out.write('Subject: testing\n')
    s.write(out, p7)
    out.close()
    print 'ok'
Пример #36
0
def load_key(file, callback=util.passphrase_callback):
    # type: (AnyStr, Callable) -> RSA
    """
    Load an RSA key pair from file.

    :param file: Name of file containing RSA public key in PEM format.

    :param callback: A Python callable object that is invoked
                     to acquire a passphrase with which to unlock the
                     key.  The default is util.passphrase_callback.

    :return: M2Crypto.RSA.RSA object.
    """
    with BIO.openfile(file) as bio:
        return load_key_bio(bio, callback)
Пример #37
0
def load_crl(file):
    # type: (AnyStr) -> CRL
    """
    Load CRL from file.

    @param file: Name of file containing CRL in PEM format.

    @return: M2Crypto.X509.CRL object.
    """
    with BIO.openfile(file) as f:
        cptr = m2.x509_crl_read_pem(f.bio_ptr())

    if cptr is None:
        raise X509Error(Err.get_error())
    return CRL(cptr, 1)
Пример #38
0
def load_request(file):
    """
    Load certificate request from file.

    @type file: string
    @param file: Name of file containing certificate request in PEM format.

    @rtype: M2Crypto.X509.Request
    @return: M2Crypto.X509.Request object.
    """
    f = BIO.openfile(file)
    cptr = m2.x509_req_read_pem(f.bio_ptr())
    f.close()
    if cptr is None:
        raise Err.get_error()
    return Request(cptr, 1)
Пример #39
0
def load_crl(file):
    """
    Load CRL from file.

    @type file: string
    @param file: Name of file containing CRL in PEM format.

    @rtype: M2Crypto.X509.CRL
    @return: M2Crypto.X509.CRL object.
    """
    f = BIO.openfile(file)
    cptr = m2.x509_crl_read_pem(f.bio_ptr())
    f.close()
    if cptr is None:
        raise X509Error(Err.get_error())
    return CRL(cptr, 1)
Пример #40
0
def load_params(file, callback=util.passphrase_callback):
    # type: (AnyStr, Callable) -> DSA
    """
    Factory function that instantiates a DSA object with DSA
    parameters from a file.

    @param file:     Names the file (a path) that contains the PEM
                     representation of the DSA parameters.
    @param callback: A Python callback object that will be
                     invoked if the DSA parameters file is
                     passphrase-protected.
    @return:         instance of DSA.
    """
    with BIO.openfile(file) as bio:
        ret = load_params_bio(bio, callback)

    return ret
Пример #41
0
def load_key(file, callback=util.passphrase_callback):
    # type: (AnyStr, Callable) -> PKey
    """
    Load an M2Crypto.EVP.PKey from file.

    :param file: Name of file containing the key in PEM format.

    :param callback: A Python callable object that is invoked
                     to acquire a passphrase with which to protect the
                     key.

    :return: M2Crypto.EVP.PKey object.
    """
    with BIO.openfile(file, 'r') as bio:
        cptr = m2.pkey_read_pem(bio.bio, callback)

    return PKey(cptr, 1)
Пример #42
0
def load_key(file, callback=util.passphrase_callback):
    # type: (AnyStr, Callable) -> DSA
    """
    Factory function that instantiates a DSA object from a
    PEM encoded DSA key pair.

    :param file:     Names the file (a path) that contains the PEM
                     representation of the DSA key pair.
    :param callback: A Python callback object that will be
                     invoked if the DSA key pair is
                     passphrase-protected.
    :return:         instance of DSA.
    """
    with BIO.openfile(file) as bio:
        ret = load_key_bio(bio, callback)

    return ret
Пример #43
0
    def save_key(self,
                 filename,
                 cipher='aes_128_cbc',
                 callback=util.passphrase_callback):
        # type: (AnyStr, str, Callable) -> int
        """
        Save the DSA key pair to a file.

        :param filename: Save the DSA key pair to this file.
        :param cipher:   name of symmetric key algorithm and mode
                         to encrypt the private key.
        :return:         1 (true) if successful
        """
        with BIO.openfile(filename, 'wb') as bio:
            ret = self.save_key_bio(bio, cipher, callback)

        return ret
Пример #44
0
def load_key(file, callback=util.passphrase_callback):
    """
    Load an RSA key pair from file.

    @type file: string
    @param file: Name of file containing RSA public key in PEM format.

    @type callback: Python callable
    @param callback: A Python callable object that is invoked
    to acquire a passphrase with which to unlock the key.
    The default is util.passphrase_callback.

    @rtype: M2Crypto.RSA.RSA
    @return: M2Crypto.RSA.RSA object.
    """
    bio = BIO.openfile(file)
    return load_key_bio(bio, callback)
Пример #45
0
    def save_key(self, file, cipher='aes_128_cbc',
                 callback=util.passphrase_callback):
        # type: (AnyStr, Optional[str], Callable) -> int
        """
        Save the key pair to a file in PEM format.

        @param file: Name of file to save key to.

        @param cipher: Symmetric cipher to protect the key. The default
        cipher is 'aes_128_cbc'. If cipher is None, then the key is saved
        in the clear.

        @param callback: A Python callable object that is invoked
        to acquire a passphrase with which to protect the key.
        The default is util.passphrase_callback.
        """
        with BIO.openfile(file, 'wb') as bio:
            return self.save_key_bio(bio, cipher, callback)
Пример #46
0
def load_pub_key(file, callback=util.passphrase_callback):
    # type: (AnyStr, Callable) -> DSA_pub
    """
    Factory function that instantiates a DSA_pub object using
    a DSA public key contained in PEM file.  The PEM file
    must contain the parameters in addition to the public key.

    :param file:     Names the file (a path) that contains the PEM
                     representation of the DSA public key.
    :param callback: A Python callback object that will be
                     invoked should the DSA public key be
                     passphrase-protected.
    :return:         instance of DSA_pub.
    """
    with BIO.openfile(file) as bio:
        ret = load_pub_key_bio(bio, callback)

    return ret
Пример #47
0
    def save_key(self,
                 filename,
                 cipher='aes_128_cbc',
                 callback=util.passphrase_callback):
        """
        Save the DSA key pair to a file.

        @type  filename: str
        @param filename: Save the DSA key pair to this file.
        @type  cipher:   str
        @param cipher:   name of symmetric key algorithm and mode
                         to encrypt the private key.
        @return:         1 (true) if successful
        """
        bio = BIO.openfile(filename, 'wb')
        ret = self.save_key_bio(bio, cipher, callback)
        bio.close()
        return ret
Пример #48
0
def load_key_pubkey(file, callback=util.passphrase_callback):
    # type: (AnyStr, Callable) -> PKey
    """
    Load an M2Crypto.EVP.PKey from a public key as a file.

    :param file: Name of file containing the key in PEM format.

    :param callback: A Python callable object that is invoked
                     to acquire a passphrase with which to protect the
                     key.

    :return: M2Crypto.EVP.PKey object.
    """

    with BIO.openfile(file, 'r') as bio:
        cptr = m2.pkey_read_pem_pubkey(bio._ptr(), callback)
        if cptr is None:
            raise EVPError(Err.get_error())
    return PKey(cptr, 1)
Пример #49
0
def load_key(file, callback=util.passphrase_callback):
    """
    Factory function that instantiates a DSA object from a
    PEM encoded DSA key pair.

    @type  file:     str
    @param file:     Names the file (a path) that contains the PEM
                     representation of the DSA key pair.
    @type  callback: A Python callable
    @param callback: A Python callback object that will be
                     invoked if the DSA key pair is
                     passphrase-protected.
    @rtype:          DSA
    @return:         instance of DSA.
    """
    bio = BIO.openfile(file)
    ret = load_key_bio(bio, callback)
    bio.close()
    return ret
Пример #50
0
def _get_x509_list(cert):
    x509_list = []
    fd = BIO.openfile(cert, 'rb')
    cert = X509.load_cert_bio(fd)
    try:
        while True:
            x509_list.append(cert)
            log.debug("Loaded " + cert.get_subject().as_text())
            cert = X509.load_cert_bio(fd)
    except X509.X509Error:
        # When there are no more certs, this is what we get, so it is fine
        pass
    except BIO.BIOError:
        # When there are no more certs, this is what we get, so it is fine
        # Python 2.4
        pass

    del fd
    return x509_list
Пример #51
0
    def save(self, filename, format=FORMAT_PEM):
        """
        Saves X.509 certificate request to a file. Default output
        format is PEM.

        @type filename: string
        @param filename: Name of the file the request will be saved to.
        @type format: int
        @param format: Controls what output format is used to save the request.
        Either FORMAT_PEM or FORMAT_DER to save in PEM or DER format.
        Raises ValueError if an unknown format is used.
        """
        bio = BIO.openfile(filename, 'wb')
        if format == FORMAT_PEM:
            return m2.x509_req_write_pem(bio.bio_ptr(), self.req)
        elif format == FORMAT_DER:
            return m2.i2d_x509_req_bio(bio.bio_ptr(), self.req)
        else:
            raise ValueError(
                "Unknown filetype. Must be either FORMAT_DER or FORMAT_PEM")
Пример #52
0
    def save(self, filename, format=FORMAT_PEM):
        # type: (AnyStr, int) -> int
        """
        Saves X.509 certificate to a file. Default output
        format is PEM.

        @param filename: Name of the file the cert will be saved to.
        @param format: Controls what output format is used to save the cert.
        Either FORMAT_PEM or FORMAT_DER to save in PEM or DER format.
        Raises a ValueError if an unknow format is used.
        @return: 1 for success or 0 for failure
        """
        with BIO.openfile(filename, 'wb') as bio:
            if format == FORMAT_PEM:
                return m2.x509_write_pem(bio.bio_ptr(), self.x509)
            elif format == FORMAT_DER:
                return m2.i2d_x509_bio(bio.bio_ptr(), self.x509)
            else:
                raise ValueError(
                    "Unknown filetype. Must be either FORMAT_PEM or FORMAT_DER")
Пример #53
0
def load_pub_key(file, callback=util.passphrase_callback):
    """
    Factory function that instantiates a DSA_pub object using
    a DSA public key contained in PEM file.  The PEM file
    must contain the parameters in addition to the public key.

    @type  file:     str
    @param file:     Names the file (a path) that contains the PEM
                     representation of the DSA public key.
    @type  callback: A Python callable
    @param callback: A Python callback object that will be
                     invoked should the DSA public key be
                     passphrase-protected.
    @rtype:          DSA_pub
    @return:         instance of DSA_pub.
    """
    bio = BIO.openfile(file)
    ret = load_pub_key_bio(bio, callback)
    bio.close()
    return ret
Пример #54
0
    def save_key(self, file, cipher='aes_128_cbc',
                 callback=util.passphrase_callback):
        """
        Save the key pair to a file in PEM format.

        @type file: string
        @param file: Name of file to save key to.

        @type cipher: string
        @param cipher: Symmetric cipher to protect the key. The default
        cipher is 'aes_128_cbc'. If cipher is None, then the key is saved
        in the clear.

        @type callback: Python callable
        @param callback: A Python callable object that is invoked
        to acquire a passphrase with which to protect the key.
        The default is util.passphrase_callback.
        """
        bio = BIO.openfile(file, 'wb')
        return self.save_key_bio(bio, cipher, callback)
Пример #55
0
    def save(self, filename, format=FORMAT_PEM):
        # type: (AnyStr, int) -> int
        """
        Saves X.509 certificate request to a file. Default output
        format is PEM.

        @param filename: Name of the file the request will be saved to.
        @param format: Controls what output format is used to save the request.
        Either FORMAT_PEM or FORMAT_DER to save in PEM or DER format.
        Raises ValueError if an unknown format is used.
        @return: 1 for success, 0 for failure.
                 The error code can be obtained by ERR_get_error.
        """
        with BIO.openfile(filename, 'wb') as bio:
            if format == FORMAT_PEM:
                return m2.x509_req_write_pem(bio.bio_ptr(), self.req)
            elif format == FORMAT_DER:
                return m2.i2d_x509_req_bio(bio.bio_ptr(), self.req)
            else:
                raise ValueError(
                    "Unknown filetype. Must be either FORMAT_DER or FORMAT_PEM")
Пример #56
0
def load_request(file, format=FORMAT_PEM):
    # type: (AnyStr, int) -> Request
    """
    Load certificate request from file.

    :param file: Name of file containing certificate request in
                 either PEM or DER format.
    :param format: Describes the format of the file to be loaded,
                   either PEM or DER. (using constants FORMAT_PEM
                   and FORMAT_DER)
    :return: Request object.
    """
    with BIO.openfile(file) as f:
        if format == FORMAT_PEM:
            cptr = m2.x509_req_read_pem(f.bio_ptr())
        elif format == FORMAT_DER:
            cptr = m2.d2i_x509_req(f.bio_ptr())
        else:
            raise ValueError(
                "Unknown filetype. Must be either FORMAT_PEM or FORMAT_DER")

    return Request(cptr, 1)
Пример #57
0
def load_cert(file, format=FORMAT_PEM):
    # type: (AnyStr, int) -> X509
    """
    Load certificate from file.

    :param file: Name of file containing certificate in either DER or
                 PEM format.

    :param format: Describes the format of the file to be loaded,
                   either PEM or DER.

    :return: M2Crypto.X509.X509 object.
    """
    with BIO.openfile(file) as bio:
        if format == FORMAT_PEM:
            return load_cert_bio(bio)
        elif format == FORMAT_DER:
            cptr = m2.d2i_x509(bio._ptr())
            return X509(cptr, _pyfree=1)
        else:
            raise ValueError(
                "Unknown format. Must be either FORMAT_DER or FORMAT_PEM")
Пример #58
0
def load_cert(file, format=FORMAT_PEM):
    """
    Load certificate from file.

    @type file: string
    @param file: Name of file containing certificate in either DER or PEM format.
    @type format: int, either FORMAT_PEM or FORMAT_DER
    @param format: Describes the format of the file to be loaded, either PEM or DER.

    @rtype: M2Crypto.X509.X509
    @return: M2Crypto.X509.X509 object.
    """
    bio = BIO.openfile(file)
    if format == FORMAT_PEM:
        return load_cert_bio(bio)
    elif format == FORMAT_DER:
        cptr = m2.d2i_x509(bio._ptr())
        if cptr is None:
            raise X509Error(Err.get_error())
        return X509(cptr, _pyfree=1)
    else:
        raise ValueError(
            "Unknown format. Must be either FORMAT_DER or FORMAT_PEM")
Пример #59
0
def load_request(file, format=FORMAT_PEM):
    """
    Load certificate request from file.

    @type file: string
    @param file: Name of file containing certificate request in either PEM or DER format.
    @type format: int, either FORMAT_PEM or FORMAT_DER
    @param format: Describes the format of the file to be loaded, either PEM or DER.

    @rtype: M2Crypto.X509.Request
    @return: M2Crypto.X509.Request object.
    """
    f = BIO.openfile(file)
    if format == FORMAT_PEM:
        cptr = m2.x509_req_read_pem(f.bio_ptr())
    elif format == FORMAT_DER:
        cptr = m2.d2i_x509_req(f.bio_ptr())
    else:
        raise ValueError(
            "Unknown filetype. Must be either FORMAT_PEM or FORMAT_DER")
    f.close()
    if cptr is None:
        raise X509Error(Err.get_error())
    return Request(cptr, 1)
Пример #60
0
def sign(private_key_path, certificate_path, request_path):
    if not get_extension(certificate_path, 'keyUsage') == 'Digital Signature':
        print(
            'ERROR sign: key pair %s and %s could not be used for signing file because policy'
            % (private_key_path, certificate_path))
        exit(1)
    request = None
    try:
        request = X509.load_request(request_path)
    except (IOError, X509.X509Error):
        print('ERROR sign: Could not load request from %s' % request_path)
        exit(1)
    text = BIO.MemoryBuffer(request.as_pem())
    smime = SMIME.SMIME()
    try:
        smime.load_key(private_key_path, certificate_path)
    except (ValueError, IOError, X509.X509Error):
        print('ERROR sign: Could not load digital signature')
        exit(1)
    sign_request = smime.sign(text)
    sign_request_file = BIO.openfile(request_path + '.sign', 'w')
    smime.write(sign_request_file, sign_request)
    sign_request_file.close()
    print('Signing request was saved to %s' % request_path + '.sign')