Loads an SSL context from a certificate and private key file.
498290
def load_ssl_context(cert_file, pkey_file):
    """"""
    from OpenSSL import SSL
    ctx = SSL.Context(SSL.SSLv23_METHOD)
    ctx.use_certificate_file(cert_file)
    ctx.use_privatekey_file(pkey_file)
    return ctx
1193225
public static PublicKey loadPublicKeyFromCert(String certPath) throws CertificateException, FileNotFoundException {
    	try {			
    		CertificateFactory cf = CertificateFactory.getInstance("X.509");
    		FileInputStream in = new FileInputStream(certPath);
    		Certificate crt = cf.generateCertificate(in);
    		PublicKey publicKey = crt.getPublicKey();
    		return publicKey;
		} catch (CertificateException e) {
			throw new RuntimeException(e);
		}catch (FileNotFoundException e) {
			throw new RuntimeException("文件不存在");
		}
	}
100320
function (context, run, done) {
        var request,
            pfxPath,
            keyPath,
            certPath,
            fileResolver,

            certificate;

        // A. Check if we have the file resolver
        fileResolver = run.options.fileResolver;

        if (!fileResolver) { return done(); } // No point going ahead

        // B. Ensure we have the request
        request = _.get(context.item, 'request');
        if (!request) { return done(new Error('No request to resolve certificates for.')); }

        // C. See if any cert should be sent, by performing a URL matching
        certificate = run.options.certificates && run.options.certificates.resolveOne(request.url);
        if (!certificate) { return done(); }

        // D. Fetch the paths
        // @todo: check why aren't we reading ca file (why are we not supporting ca file)
        pfxPath = _.get(certificate, 'pfx.src');
        keyPath = _.get(certificate, 'key.src');
        certPath = _.get(certificate, 'cert.src');

        // E. Read from the path, and add the values to the certificate, also associate
        // the certificate with the current request.
        async.mapValues({
            pfx: pfxPath,
            key: keyPath,
            cert: certPath
        }, function (value, key, next) {
            // bail out if value is not defined
            // @todo add test with server which only accepts cert file
            if (!value) { return next(); }

            // eslint-disable-next-line security/detect-non-literal-fs-filename
            fileResolver.readFile(value, function (err, data) {
                // Swallow the error after triggering a warning message for the user.
                err && run.triggers.console(context.coords, 'warn',
                    `certificate "${key}" load error:  ${(err.message || err)}`);
                next(null, data);
            });
        }, function (err, fileContents) {
            if (err) {
                // Swallow the error after triggering a warning message for the user.
                run.triggers.console(context.coords, 'warn', 'certificate load error: ' + (err.message || err));

                return done();
            }

            if (fileContents) {
                !_.isNil(fileContents.pfx) && _.set(certificate, 'pfx.value', fileContents.pfx);
                !_.isNil(fileContents.key) && _.set(certificate, 'key.value', fileContents.key);
                !_.isNil(fileContents.cert) && _.set(certificate, 'cert.value', fileContents.cert);

                (fileContents.cert || fileContents.key || fileContents.pfx) && (request.certificate = certificate);
            }
            done();
        });
    }
197513
private static PrivateKey loadPrivateKey(byte[] keyBytes) {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
                keyBytes);
        try {
            KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
            PrivateKey privateKey = factory
                    .generatePrivate(pkcs8EncodedKeySpec);
            return privateKey;
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
35208
def load_key(self, key_path, password):
        

        try:
            return paramiko.RSAKey.from_private_key_file(key_path)
        except PasswordRequiredException as ex:
            return paramiko.RSAKey.from_private_key_file(key_path,
                                                         password=password)
758595
private SslContext getSslContext() {
        final SslContext sslCtx;
        if (clientConfig.isEnableTls()) {
            try {
                SslContextBuilder clientSslCtxBuilder = SslContextBuilder.forClient();
                if (Strings.isNullOrEmpty(clientConfig.getTrustStore())) {
                    clientSslCtxBuilder = clientSslCtxBuilder.trustManager(FingerprintTrustManagerFactory
                                                                                   .getInstance(FingerprintTrustManagerFactory.getDefaultAlgorithm()));
                    log.debug("SslContextBuilder was set to an instance of {}", FingerprintTrustManagerFactory.class);
                } else {
                    clientSslCtxBuilder = SslContextBuilder.forClient()
                                                           .trustManager(new File(clientConfig.getTrustStore()));
                }
                sslCtx = clientSslCtxBuilder.build();
            } catch (SSLException | NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            }
        } else {
            sslCtx = null;
        }
        return sslCtx;
    }
286346
def load_credential_file(self, path):
        """"""
        c_data = StringIO.StringIO()
        c_data.write("[Credentials]\n")
        for line in open(path, "r").readlines():
            c_data.write(line.replace("AWSAccessKeyId", "aws_access_key_id").replace("AWSSecretKey", "aws_secret_access_key"))
        c_data.seek(0)
        self.readfp(c_data)
1310942
def _init_client_authentication(
            self,
            client_certchain_file: Optional[str],
            client_key_file: Optional[str],
            client_key_type: OpenSslFileTypeEnum,
            client_key_password: str,
            ignore_client_authentication_requests: bool
    ) -> None:
        
        if client_certchain_file is not None and client_key_file is not None:
            self._use_private_key(client_certchain_file, client_key_file, client_key_type, client_key_password)

        if ignore_client_authentication_requests:
            if client_certchain_file:
                raise ValueError('Cannot enable both client_certchain_file and ignore_client_authentication_requests')

            self._ssl_ctx.set_client_cert_cb_NULL()
875577
def _init_ssl(self):
        

        if not have_openssl:
            raise ImportError('SSL sockets have been disabled due to missing requirement: pyopenssl.')

        try:
            ctx = SSL.Context(SSL.TLSv1_METHOD)

            if isinstance(self.ssl_key, crypto.PKey):
                ctx.use_privatekey(self.ssl_key)
            else:
                ctx.use_privatekey_file(self.ssl_key)

            if isinstance(self.ssl_certificate, crypto.X509):
                ctx.use_certificate(self.ssl_certificate)
            else:
                ctx.use_certificate_file(self.ssl_certificate)

            if isinstance(self.ssl_ca, crypto.X509):
                store = ctx.get_cert_store()
                store.add_cert(self.ssl_ca)
            else:
                ctx.load_verify_locations(self.ssl_ca, None)

            verify_method = SSL.VERIFY_PEER
            if (self._ssl_allow_self_signed):
                verify_method = SSL.VERIFY_NONE

            ctx.set_verify(verify_method, self._verify_ssl_callback)

            self._device = SSL.Connection(ctx, self._device)

        except SSL.Error as err:
            raise CommError('Error setting up SSL connection.', err)
1309844
def generate_adhoc_ssl_context():
    """"""
    crypto = _get_openssl_crypto_module()
    import tempfile
    import atexit

    cert, pkey = generate_adhoc_ssl_pair()
    cert_handle, cert_file = tempfile.mkstemp()
    pkey_handle, pkey_file = tempfile.mkstemp()
    atexit.register(os.remove, pkey_file)
    atexit.register(os.remove, cert_file)

    os.write(cert_handle, crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    os.write(pkey_handle, crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
    os.close(cert_handle)
    os.close(pkey_handle)
    ctx = load_ssl_context(cert_file, pkey_file)
    return ctx
105058
def _docker_machine_ssl_context():
        
        context = ssl.SSLContext(ssl.PROTOCOL_TLS)
        context.set_ciphers(ssl._RESTRICTED_SERVER_CIPHERS)
        certs_path = os.environ.get("DOCKER_CERT_PATH", None)
        if certs_path is None:
            raise ValueError(
                "Cannot create ssl context, " "DOCKER_CERT_PATH is not set!"
            )
        certs_path = Path(certs_path)
        context.load_verify_locations(cafile=certs_path / "ca.pem")
        context.load_cert_chain(
            certfile=certs_path / "cert.pem", keyfile=certs_path / "key.pem"
        )
        return context
1056943
def verify_cert(self):
        '''
        
        '''
        log.debug('Verifying the %s certificate, keyfile: %s',
                  self.certificate, self.keyfile)
        try:
            ssl.create_default_context().load_cert_chain(self.certificate, keyfile=self.keyfile)
        except ssl.SSLError:
            error_string = 'SSL certificate and key do not match'
            log.error(error_string)
            raise SSLMismatchException(error_string)
        except IOError:
            log.error('Unable to open either certificate or key file')
            raise
        log.debug('Certificate looks good.')
33066
def create_tls_context(self):
        
        # Create context manually, as we're going to set our own options.
        tls_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)

        # Load client/server certificate.
        if self.tls_certificate_file:
            tls_context.load_cert_chain(self.tls_certificate_file, self.tls_certificate_keyfile,
                                        password=self.tls_certificate_password)

        # Set some relevant options:
        # - No server should use SSLv2 or SSLv3 any more, they are outdated and full of security holes. (RFC6176, RFC7568)
        # - Disable compression in order to counter the CRIME attack. (https://en.wikipedia.org/wiki/CRIME_%28security_exploit%29)
        # - Disable session resumption to maintain perfect forward secrecy. (https://timtaubert.de/blog/2014/11/the-sad-state-of-server-side-tls-session-resumption-implementations/)
        for opt in ['NO_SSLv2', 'NO_SSLv3', 'NO_COMPRESSION', 'NO_TICKET']:
            if hasattr(ssl, 'OP_' + opt):
                tls_context.options |= getattr(ssl, 'OP_' + opt)

        # Set TLS verification options.
        if self.tls_verify:
            # Set our custom verification callback, if the library supports it.
            tls_context.set_servername_callback(self.verify_tls)

            # Load certificate verification paths.
            tls_context.set_default_verify_paths()
            if sys.platform in DEFAULT_CA_PATHS and path.isdir(DEFAULT_CA_PATHS[sys.platform]):
                tls_context.load_verify_locations(capath=DEFAULT_CA_PATHS[sys.platform])

            # If we want to verify the TLS connection, we first need a certicate.
            # Check this certificate and its entire chain, if possible, against revocation lists.
            tls_context.verify_mode = ssl.CERT_REQUIRED
            tls_context.verify_flags = ssl.VERIFY_CRL_CHECK_CHAIN

        return tls_context
1080196
function loadKeyPair (pub, prv, use) {
  var pubPEM, prvPEM, pubJWK

  try {
    pubPEM = fs.readFileSync(pub).toString('ascii')
  } catch (e) {
    throw new Error('Unable to read the public key from ' + pub)
  }

  try {
    prvPEM = fs.readFileSync(prv).toString('ascii')
  } catch (e) {
    throw new Error('Unable to read the private key from ' + pub)
  }

  try {
    pubJWK = pemjwk.pem2jwk(pubPEM)
  } catch (e) {
    throw new Error('Unable to convert the public key ' + pub + ' to a JWK')
  }

  return {
    pem: {
      pub: pubPEM,
      prv: prvPEM
    },
    jwk: {
      pub: {
        kty: pubJWK.kty,
        use: use,
        alg: 'RS256',
        n: pubJWK.n,
        e: pubJWK.e
      }
    }
  }
}
53076
def getContext(self):
        """"""
        ctx = SSL.Context(SSL.SSLv23_METHOD)
        ctx.use_certificate_file('server.pem')
        ctx.use_privatekey_file('server.pem')
        return ctx
72185
public static void loadX509Cert( File certFile, KeyStore keyStore ) throws GeneralSecurityException, IOException
    {
        try ( BufferedInputStream inputStream = new BufferedInputStream( new FileInputStream( certFile ) ) )
        {
            CertificateFactory certFactory = CertificateFactory.getInstance( "X.509" );

            int certCount = 0; // The file might contain multiple certs
            while ( inputStream.available() > 0 )
            {
                try
                {
                    Certificate cert = certFactory.generateCertificate( inputStream );
                    certCount++;
                    loadX509Cert( cert, "neo4j.javadriver.trustedcert." + certCount, keyStore );
                }
                catch ( CertificateException e )
                {
                    if ( e.getCause() != null && e.getCause().getMessage().equals( "Empty input" ) )
                    {
                        // This happens if there is whitespace at the end of the certificate - we load one cert, and then try and load a
                        // second cert, at which point we fail
                        return;
                    }
                    throw new IOException( "Failed to load certificate from `" + certFile.getAbsolutePath() + "`: " + certCount + " : " + e.getMessage(), e );
                }
            }
        }
    }
1370806
def validate(cert, ca_name, crl_file):
    '''
    
    '''
    store = OpenSSL.crypto.X509Store()
    cert_obj = _read_cert(cert)
    if cert_obj is None:
        raise CommandExecutionError(
            'Failed to read cert from {0}, see log for details'.format(cert)
        )
    ca_dir = '{0}/{1}'.format(cert_base_path(), ca_name)
    ca_cert = _read_cert('{0}/{1}_ca_cert.crt'.format(ca_dir, ca_name))
    store.add_cert(ca_cert)
    # These flags tell OpenSSL to check the leaf as well as the
    # entire cert chain.
    X509StoreFlags = OpenSSL.crypto.X509StoreFlags
    store.set_flags(X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
    if crl_file is None:
        crl = OpenSSL.crypto.CRL()
    else:
        with salt.utils.files.fopen(crl_file) as fhr:
            crl = OpenSSL.crypto.load_crl(OpenSSL.crypto.FILETYPE_PEM, fhr.read())
    store.add_crl(crl)
    context = OpenSSL.crypto.X509StoreContext(store, cert_obj)
    ret = {}
    try:
        context.verify_certificate()
        ret['valid'] = True
    except OpenSSL.crypto.X509StoreContextError as e:
        ret['error'] = str(e)
        ret['error_cert'] = e.certificate
        ret['valid'] = False
    return ret