Insert certificate into certificate store in memory. Note that this
does not save the certificate to disk. To do that, use zcert_save()
directly on the certificate. Takes ownership of zcert_t object.
326992
def insert(self, cert_p):
        
        return lib.zcertstore_insert(self._as_parameter_, byref(zcert_p.from_param(cert_p)))
1047294
def save( self ):
        
        packets = self.__enumerate_packets( )
        delete_io( self.hash )
        for packet in packets:
            packet['hash'] = self.hash
            insert_io( packet )

        return self
1365134
def save(self, cachedir=None, cfgstr=None, verbose=VERBOSE, quiet=QUIET,
             ignore_keys=None):
        
        fpath = self.get_fpath(cachedir, cfgstr=cfgstr)
        if verbose:
            print('[Cachable] cache save: %r' % (basename(fpath),))

        if hasattr(self, '__getstate__'):
            statedict = self.__getstate__()
        else:
            statedict = self.__dict__

        if ignore_keys is None:
            save_dict = statedict
        else:
            save_dict = {key: val
                         for (key, val) in six.iteritems(statedict)
                         if key not in ignore_keys}

        util_io.save_data(fpath, save_dict)
        return fpath
706729
def save(self):
        
        if self.parent.buffered:
            query = """
                INSERT DATA { GRAPH %s { %s } }
            """
            query = query % (self.identifier.n3(),
                             self.graph.serialize(format='nt'))
            self.parent.graph.update(query)
            self.flush()
        else:
            self.meta.generate()
795650
def addcert(self, cert):
        
        if libcrypto.CMS_add1_cert(self.ptr, cert.cert) <= 0:
            raise CMSError("Cannot add cert")
143525
def verify_certificate_chain(cert_str, trusted_certs, ignore_self_signed=True):
    

    # Load the certificate
    certificate = crypto.load_certificate(crypto.FILETYPE_ASN1, cert_str)

    # Create a certificate store and add your trusted certs
    try:
        store = crypto.X509Store()

        if ignore_self_signed:
            store.add_cert(certificate)

        # Assuming the certificates are in PEM format in a trusted_certs list
        for _cert in trusted_certs:
            store.add_cert(
                crypto.load_certificate(crypto.FILETYPE_ASN1, _cert))

        # Create a certificate context using the store and the certificate
        store_ctx = crypto.X509StoreContext(store, certificate)

        # Verify the certificate, returns None if certificate is not valid
        store_ctx.verify_certificate()

        return True

    except crypto.X509StoreContextError as e:
        raise AS2Exception('Partner Certificate Invalid: %s' % e.args[-1][-1])
547815
def save_x509s(self, x509s):
        """"""

        for file_type in TLSFileType:
            if file_type.value in x509s:
                x509 = x509s[file_type.value]
                if file_type is not TLSFileType.CA:
                    # persist this key or cert to disk
                    tlsfile = getattr(self, file_type.value)
                    if tlsfile:
                        tlsfile.save(x509)
584431
private Certificate generateCertificate()
            throws IOException, CertificateException {
        InputStream caInput = null;
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            caInput = new ByteArrayInputStream(caCertificate.getBytes("UTF-8"));
            return cf.generateCertificate(caInput);
        } finally {
            IOUtil.closeResource(caInput);
        }
    }
1020430
def import_certificate(
        ctx, slot, management_key, pin, cert, password, verify):
    
    controller = ctx.obj['controller']
    _ensure_authenticated(ctx, controller, pin, management_key)

    data = cert.read()

    while True:
        if password is not None:
            password = password.encode()
        try:
            certs = parse_certificates(data, password)
        except (ValueError, TypeError):
            if password is None:
                password = click.prompt(
                    'Enter password to decrypt certificate',
                    default='', hide_input=True,
                    show_default=False,
                    err=True)
                continue
            else:
                password = None
                click.echo('Wrong password.')
            continue
        break

    if len(certs) > 1:
        #  If multiple certs, only import leaf.
        #  Leaf is the cert with a subject that is not an issuer in the chain.
        leafs = get_leaf_certificates(certs)
        cert_to_import = leafs[0]
    else:
        cert_to_import = certs[0]

    def do_import(retry=True):
        try:
            controller.import_certificate(
                slot, cert_to_import, verify=verify,
                touch_callback=prompt_for_touch)

        except KeypairMismatch:
            ctx.fail('This certificate is not tied to the private key in the '
                     '{} slot.'.format(slot.name))

        except APDUError as e:
            if e.sw == SW.SECURITY_CONDITION_NOT_SATISFIED and retry:
                _verify_pin(ctx, controller, pin)
                do_import(retry=False)
            else:
                raise

    do_import()
1254038
synchronized KeyAndCertificateFactory buildAndSaveCertificates() {
        try {
            // personal keys
            KeyPair keyPair = generateKeyPair(FAKE_KEYSIZE);
            PrivateKey mockServerPrivateKey = keyPair.getPrivate();
            PublicKey mockServerPublicKey = keyPair.getPublic();

            // ca keys
            PrivateKey caPrivateKey = loadPrivateKeyFromPEMFile("org/mockserver/socket/CertificateAuthorityPrivateKey.pem");
            X509Certificate caCert = loadX509FromPEMFile("org/mockserver/socket/CertificateAuthorityCertificate.pem");

            // generate mockServer certificate
            X509Certificate mockServerCert = createCASignedCert(
                mockServerPublicKey,
                caCert,
                caPrivateKey,
                caCert.getPublicKey(),
                ConfigurationProperties.sslCertificateDomainName(),
                ConfigurationProperties.sslSubjectAlternativeNameDomains(),
                ConfigurationProperties.sslSubjectAlternativeNameIps()
            );
            String randomUUID = UUID.randomUUID().toString();
            mockServerCertificatePEMFile = saveCertificateAsPEMFile(mockServerCert, "MockServerCertificate" + randomUUID + ".pem", true);
            mockServerPublicKeyPEMFile = saveCertificateAsPEMFile(mockServerPublicKey, "MockServerPublicKey" + randomUUID + ".pem", true);
            mockServerPrivateKeyPEMFile = saveCertificateAsPEMFile(mockServerPrivateKey, "MockServerPrivateKey" + randomUUID + ".pem", true);
        } catch (Exception e) {
            MOCK_SERVER_LOGGER.error("Error while refreshing certificates", e);
        }
        return this;
    }
358251
public void put(GSSCredential credential,
                    InitParams params)
        throws MyProxyException {

        if (credential == null) {
            throw new IllegalArgumentException("credential == null");
        }

        if (params == null) {
            throw new IllegalArgumentException("params == null");
        }

        if (!(credential instanceof GlobusGSSCredentialImpl)) {
            throw new IllegalArgumentException("wrong type of credentials");
        }

        String msg = params.makeRequest();

        Socket gsiSocket = null;
        OutputStream out = null;
        InputStream  in  = null;

        try {
            gsiSocket = getSocket(credential);

            out = gsiSocket.getOutputStream();
            in  = gsiSocket.getInputStream();

            if (!((GssSocket)gsiSocket).getContext().getConfState())
                throw new Exception("Confidentiality requested but not available");

            // send message
            out.write(msg.getBytes());
            out.flush();

            if (logger.isDebugEnabled()) {
                logger.debug("Req sent:" + params);
            }

            handleReply(in);

            BouncyCastleCertProcessingFactory certFactory =
                BouncyCastleCertProcessingFactory.getDefault();

            GlobusGSSCredentialImpl pkiCred =
                (GlobusGSSCredentialImpl)credential;

            X509Certificate [] certs = pkiCred.getCertificateChain();

            // read in the cert request from socket and
            // generate a certificate to be sent back to the server
            X509Certificate cert =
                certFactory.createCertificate(in,
                                              certs[0],
                                              pkiCred.getPrivateKey(),
                                              -1,
                     BouncyCastleCertProcessingFactory.decideProxyType(certs[0],
                                             GSIConstants.DelegationType.FULL));

            // write the new cert we've generated to the socket to send it back
            // to the server

            // must put everything into one message
            ByteArrayOutputStream buffer = new ByteArrayOutputStream(2048);

            buffer.write( (byte)(certs.length+1) );

            // write signed ceritifcate
            buffer.write(cert.getEncoded());

            for (int i=0;i<certs.length;i++) {
                buffer.write( certs[i].getEncoded() );

                // DEBUG: print out subject name of sent certificate
                if (logger.isDebugEnabled()) {
                    logger.debug("Sent cert: " + certs[i].getSubjectDN());
                }

            }

            out.write(buffer.toByteArray());
            out.flush();

            handleReply(in);

        } catch(Exception e) {
            throw new MyProxyException("MyProxy put failed.", e);
        } finally {
            // close socket
            close(out, in, gsiSocket);
        }
    }
1272437
def __insert_internal_blob(self, key, blob, compressed=True):
        ''' 
        '''
        with self.get_conn() as conn:
            conn.isolation_level = None
            c = conn.cursor()
            try:
                compressed_flag = 1 if compressed else 0
                if compressed:
                    blob = zlib.compress(blob)
                c.execute("BEGIN")
                c.execute("INSERT INTO cache_entries (key, value) VALUES (?,?)", (key, JiCache.INTERNAL_BLOB))
                c.execute("INSERT INTO blob_entries (key, compressed, blob_data) VALUES (?,?,?)", (key, compressed_flag, sqlite3.Binary(blob),))
                c.execute("COMMIT")
                return True
            except:
                getLogger().debug("Cannot insert")
                return False
1329780
public static void writeCertificate(OutputStream out,
                                        X509Certificate cert)
        throws IOException, CertificateEncodingException {
        CertificateIOUtil.writeCertificate(out, cert);
    }
1007036
def save(self, x509):
        """"""

        self.x509 = x509
        with open_tls_file(self.file_path, 'w',
                           private=self.is_private()) as fh:
            fh.write(str(self))
989454
def init(self, ca, csr, **kwargs):
        

        c = self.model(ca=ca)
        c.x509, csr = self.sign_cert(ca, csr, **kwargs)
        c.csr = csr.public_bytes(Encoding.PEM).decode('utf-8')
        c.save()

        post_issue_cert.send(sender=self.model, cert=c)
        return c
257426
def certificate(self, value):
        """"""
        import os
        if os.path.isfile(value):
            self._certificatefile = value
58199
def append(self, cert):
        

        if not isinstance(cert, x509.Certificate):
            if not isinstance(cert, byte_cls):
                raise TypeError(pretty_message(
                    '''
                    cert must be a byte string or an
                    asn1crypto.x509.Certificate object, not %s
                    ''',
                    type_name(cert)
                ))
            if pem.detect(cert):
                _, _, cert = pem.unarmor(cert)
            cert = x509.Certificate.load(cert)

        if cert.issuer_serial in self._cert_hashes:
            raise DuplicateCertificateError()

        self._cert_hashes.add(cert.issuer_serial)
        self._certs.append(cert)

        return self