当前位置: 首页>>代码示例>>C++>>正文


C++ SSL_CTX_new函数代码示例

本文整理汇总了C++中SSL_CTX_new函数的典型用法代码示例。如果您正苦于以下问题:C++ SSL_CTX_new函数的具体用法?C++ SSL_CTX_new怎么用?C++ SSL_CTX_new使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了SSL_CTX_new函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: main


//.........这里部分代码省略.........
	if (optind >= argc) {
		fprintf(stderr, "%s\n", Usage);
		exit(-1);
	}

	if (!c2c) {

		if (make_ioa_addr((const u08bits*) peer_address, peer_port, &peer_addr) < 0) {
			return -1;
		}

		if(peer_addr.ss.sa_family == AF_INET6) {
			default_address_family = STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6;
		} else if(peer_addr.ss.sa_family == AF_INET) {
			default_address_family = STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4;
		}

	}

	/* SSL Init ==>> */

	if(use_secure) {

		SSL_load_error_strings();
		OpenSSL_add_ssl_algorithms();

		const char *csuite = "ALL"; //"AES256-SHA" "DH"
		if(use_null_cipher)
			csuite = "eNULL";
		else if(cipher_suite[0])
			csuite=cipher_suite;

		if(use_tcp) {
		  root_tls_ctx[root_tls_ctx_num] = SSL_CTX_new(SSLv23_client_method());
		  SSL_CTX_set_cipher_list(root_tls_ctx[root_tls_ctx_num], csuite);
		  root_tls_ctx_num++;

		  root_tls_ctx[root_tls_ctx_num] = SSL_CTX_new(TLSv1_client_method());
		  SSL_CTX_set_cipher_list(root_tls_ctx[root_tls_ctx_num], csuite);
		  root_tls_ctx_num++;

#if TLSv1_1_SUPPORTED
		  root_tls_ctx[root_tls_ctx_num] = SSL_CTX_new(TLSv1_1_client_method());
		  SSL_CTX_set_cipher_list(root_tls_ctx[root_tls_ctx_num], csuite);
		  root_tls_ctx_num++;
#if TLSv1_2_SUPPORTED
		  root_tls_ctx[root_tls_ctx_num] = SSL_CTX_new(TLSv1_2_client_method());
		  SSL_CTX_set_cipher_list(root_tls_ctx[root_tls_ctx_num], csuite);
		  root_tls_ctx_num++;
#endif
#endif
		} else {
#if !DTLS_SUPPORTED
		  fprintf(stderr,"ERROR: DTLS is not supported.\n");
		  exit(-1);
#else
		  if(OPENSSL_VERSION_NUMBER < 0x10000000L) {
		  	TURN_LOG_FUNC(TURN_LOG_LEVEL_WARNING, "WARNING: OpenSSL version is rather old, DTLS may not be working correctly.\n");
		  }
		  root_tls_ctx[root_tls_ctx_num] = SSL_CTX_new(DTLSv1_client_method());
		  SSL_CTX_set_cipher_list(root_tls_ctx[root_tls_ctx_num], csuite);
		  root_tls_ctx_num++;
#if DTLSv1_2_SUPPORTED
		  root_tls_ctx[root_tls_ctx_num] = SSL_CTX_new(DTLSv1_2_client_method());
		  SSL_CTX_set_cipher_list(root_tls_ctx[root_tls_ctx_num], csuite);
		  root_tls_ctx_num++;
开发者ID:Acidburn0zzz,项目名称:coturn,代码行数:67,代码来源:mainuclient.c

示例2: tls_accept

BOOL tls_accept(rdpTls* tls, const char* cert_file, const char* privatekey_file)
{
	CryptoCert cert;
	long options = 0;
	int connection_status;

	tls->ctx = SSL_CTX_new(SSLv23_server_method());

	if (tls->ctx == NULL)
	{
		fprintf(stderr, "SSL_CTX_new failed\n");
		return FALSE;
	}

	/*
	 * SSL_OP_NO_SSLv2:
	 *
	 * We only want SSLv3 and TLSv1, so disable SSLv2.
	 * SSLv3 is used by, eg. Microsoft RDC for Mac OS X.
	 */
	options |= SSL_OP_NO_SSLv2;

	/**
	 * SSL_OP_NO_COMPRESSION:
	 *
	 * The Microsoft RDP server does not advertise support
	 * for TLS compression, but alternative servers may support it.
	 * This was observed between early versions of the FreeRDP server
	 * and the FreeRDP client, and caused major performance issues,
	 * which is why we're disabling it.
	 */
#ifdef SSL_OP_NO_COMPRESSION
	options |= SSL_OP_NO_COMPRESSION;
#endif
	 
	/**
	 * SSL_OP_TLS_BLOCK_PADDING_BUG:
	 *
	 * The Microsoft RDP server does *not* support TLS padding.
	 * It absolutely needs to be disabled otherwise it won't work.
	 */
	options |= SSL_OP_TLS_BLOCK_PADDING_BUG;

	/**
	 * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS:
	 *
	 * Just like TLS padding, the Microsoft RDP server does not
	 * support empty fragments. This needs to be disabled.
	 */
	options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;

	SSL_CTX_set_options(tls->ctx, options);

	if (SSL_CTX_use_RSAPrivateKey_file(tls->ctx, privatekey_file, SSL_FILETYPE_PEM) <= 0)
	{
		fprintf(stderr, "SSL_CTX_use_RSAPrivateKey_file failed\n");
		fprintf(stderr, "PrivateKeyFile: %s\n", privatekey_file);
		return FALSE;
	}

	tls->ssl = SSL_new(tls->ctx);

	if (!tls->ssl)
	{
		fprintf(stderr, "SSL_new failed\n");
		return FALSE;
	}

	if (SSL_use_certificate_file(tls->ssl, cert_file, SSL_FILETYPE_PEM) <= 0)
	{
		fprintf(stderr, "SSL_use_certificate_file failed\n");
		return FALSE;
	}

	if (SSL_set_fd(tls->ssl, tls->sockfd) < 1)
	{
		fprintf(stderr, "SSL_set_fd failed\n");
		return FALSE;
	}

	while (1)
	{
		connection_status = SSL_accept(tls->ssl);

		if (connection_status <= 0)
		{
			switch (SSL_get_error(tls->ssl, connection_status))
			{
				case SSL_ERROR_WANT_READ:
				case SSL_ERROR_WANT_WRITE:
					break;

				default:
					if (tls_print_error("SSL_accept", tls->ssl, connection_status))
						return FALSE;
					break;

			}
		}
		else
//.........这里部分代码省略.........
开发者ID:SSphere,项目名称:FreeRDP,代码行数:101,代码来源:tls.c

示例3: main

void main()
{
    int     err;
        int     verify_client = OFF; /* To verify a client certificate, set ON */
 
      int     listen_sock;
        int     sock;
       struct sockaddr_in sa_serv;
         struct sockaddr_in sa_cli;
          size_t client_len;
          char    *str;
       char     buf[4096];
 
    SSL_CTX         *ctx;
        SSL            *ssl;
       SSL_METHOD      *meth;

        X509            *client_cert = NULL;
 
   short int       s_port = 5555;
/*----------------------------------------------------------------*/
      /* Load encryption & hashing algorithms for the SSL program */
  SSL_library_init();
 
    /* Load the error strings for SSL & CRYPTO APIs */
      SSL_load_error_strings();
 
      /* Create a SSL_METHOD structure (choose a SSL/TLS protocol version) */
     meth = SSLv3_method();
 
 /* Create a SSL_CTX structure */
    ctx = SSL_CTX_new(meth);
 
       if (!ctx) {
 
            ERR_print_errors_fp(stderr);
 
           exit(1);
 
       }
 
      /* Load the server certificate into the SSL_CTX structure */
        if (SSL_CTX_use_certificate_file(ctx, RSA_SERVER_CERT, SSL_FILETYPE_PEM) <= 0) {
 
                    ERR_print_errors_fp(stderr);
 
                   exit(1);
 
       }
 
      /* Load the private-key corresponding to the server certificate */
          if (SSL_CTX_use_PrivateKey_file(ctx, RSA_SERVER_KEY, SSL_FILETYPE_PEM) <= 0) {
 
              ERR_print_errors_fp(stderr);
                exit(1);
    }
 
      /* Check if the server certificate and private-key matches */
       if (!SSL_CTX_check_private_key(ctx)) {
 
                 fprintf(stderr,"Private key does not match the certificate public key\n");
                  exit(1);
    }
 
      if(verify_client == ON)
 
        {
 
              /* Load the RSA CA certificate into the SSL_CTX structure */
                if (!SSL_CTX_load_verify_locations(ctx, RSA_SERVER_CA_CERT, NULL)) {
 
                   ERR_print_errors_fp(stderr);
                        exit(1);
            }
 
              /* Set to require peer (client) certificate verification */
         SSL_CTX_set_verify(ctx,SSL_VERIFY_PEER,NULL);
 
          /* Set the verification depth to 1 */
               SSL_CTX_set_verify_depth(ctx,1);
 
       }
   /* ----------------------------------------------- */
       /* Set up a TCP socket */
 
      listen_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);   
 
    RETURN_ERR(listen_sock, "socket");
          memset (&sa_serv, '\0', sizeof(sa_serv));
       sa_serv.sin_family      = AF_INET;
          sa_serv.sin_addr.s_addr = INADDR_ANY;
       sa_serv.sin_port        = htons (s_port);          /* Server Port number */
         err = bind(listen_sock, (struct sockaddr*)&sa_serv,sizeof(sa_serv));
 
       RETURN_ERR(err, "bind");
     
   /* Wait for an incoming TCP connection. */
          err = listen(listen_sock, 5);                    
 
      RETURN_ERR(err, "listen");
//.........这里部分代码省略.........
开发者ID:fakessh,项目名称:openprojectssl,代码行数:101,代码来源:simplesslserver.c

示例4: main

/* The program expects at most four arguments: host in IP format, port
 * number to connect to, proxy in IP format and proxy port number.
 * If last two are specified, host can be in any format proxy will
 * understand (since this is an example for SSL programming, host name
 * resolving code is left out).
 *
 * Default values are "127.0.0.1", 443. If any proxy parameter is
 * omitted, the program will connect directly to the host.
 */
int main(int argc, char *argv[])
{
	char buffer[4096]; /* This should be dynamically allocated */
	const char *request = "GET / HTTP/1.0\r\n\r\n";
	BOOL is_ok = FALSE;
	X509 *server_cert;
	SSL_CTX *ctx;
	BIO *bio_err;
	SSL *ssl;

	if (Init())
	{
		/* Basic intialization. Next few steps (up to SSL_new()) need
		 * to be done only once per AmiSSL opener.
		 */
		SSLeay_add_ssl_algorithms();
		SSL_load_error_strings();

		/* Note: BIO writing routines are prepared for NULL BIO handle */
		if((bio_err = BIO_new(BIO_s_file())) != NULL)
			BIO_set_fp_amiga(bio_err, GetStdErr(), BIO_NOCLOSE | BIO_FP_TEXT);

		/* Get a new SSL context */
		if((ctx = SSL_CTX_new(SSLv23_client_method())) != NULL)
		{
			/* Basic certificate handling. OpenSSL documentation has more
			 * information on this.
			 */
			SSL_CTX_set_default_verify_paths(ctx);
			SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
			                   NULL);

			/* The following needs to be done once per socket */
			if((ssl = SSL_new(ctx)) != NULL)
			{
				int sock;

				/* Connect to the HTTPS server, directly or through a proxy */
				if (argc > 4)
					sock = ConnectToServer(argv[1], atol(argv[2]), argv[3],
					                       atol(argv[4]));
				else
					sock = ConnectToServer(argv[1] ? argv[1] : (char *)"127.0.0.1",
					                       argc > 2 ? atol(argv[2]) : 443,
					                       NULL, 0);

				/* Check if connection was established */
				if (sock >= 0)
				{
					int ssl_err = 0;

					/* Associate the socket with the ssl structure */
					SSL_set_fd(ssl, sock);

					/* Perform SSL handshake */
					if((ssl_err = SSL_connect(ssl)) >= 0)
					{
						Printf("SSL connection using %s\n", SSL_get_cipher(ssl));

						/* Certificate checking. This example is *very* basic */
						if((server_cert = SSL_get_peer_certificate(ssl)))
						{
							char *str;

							Printf("Server certificate:\n");

							if((str = X509_NAME_oneline(X509_get_subject_name(server_cert), 0, 0)))
							{
								Printf("\tSubject: %s\n", str);
								OPENSSL_free(str);
							}
							else
								FPrintf(GetStdErr(), "Warning: couldn't read subject name in certificate!\n");

							if((str = X509_NAME_oneline(X509_get_issuer_name(server_cert),
							                            0, 0)) != NULL)
							{
								Printf("\tIssuer: %s\n", str);
								OPENSSL_free(str);
							}
							else
								FPrintf(GetStdErr(), "Warning: couldn't read issuer name in certificate!\n");

							X509_free(server_cert);

							/* Send a HTTP request. Again, this is just
							 * a very basic example.
							 */
							if ((ssl_err = SSL_write(ssl, request, strlen(request)))
							    > 0)
							{
//.........这里部分代码省略.........
开发者ID:jens-maus,项目名称:amissl,代码行数:101,代码来源:https.c

示例5: sl_ssl_server

static void sl_ssl_server (void){
  // create an ssl object and return the memory managed type back to
  // SLang. It needs the file descriptor of the object upon which
  // communication will occur, and the protocol to use
  //
  // this is the server, so it also needs the certfile and private key
  SSL_CTX *ctx;
  SSL *ssl;
  int proto, pkey_type, cert_type;
  SLang_MMT_Type *sslmmt;
  SLFile_FD_Type *slfd;
  SLsslctx_Type *slctx;
  char *pkey=NULL, *cert=NULL;

  if (SLang_pop_slstring(&pkey) == -1 ||
      SLang_pop_slstring(&cert) == -1 ||
      SLang_pop_integer(&proto) == -1){
    goto free;
    return;
  }

  if (proto==SSL_PROTO_SSL2)
    ctx = SSL_CTX_new(SSLv23_server_method());
  else if (proto==SSL_PROTO_SSL3)
    ctx = SSL_CTX_new(SSLv3_server_method());
  else if (proto==SSL_PROTO_TLS1)
    ctx = SSL_CTX_new(TLSv1_server_method());
  else if (proto==SSL_PROTO_ANY)
    ctx = SSL_CTX_new(SSLv23_server_method());

  // now add the cert file an private key
  if (1!=SSL_CTX_use_certificate_file(ctx,cert,SSL_FILETYPE_PEM))
    if (1!=SSL_CTX_use_certificate_file(ctx,cert,SSL_FILETYPE_ASN1)){
      SLang_verror(0,"Could not load certificate file");
      goto free;
    }
  if (1!=SSL_CTX_use_PrivateKey_file(ctx,pkey,SSL_FILETYPE_PEM))
    if (1!=SSL_CTX_use_PrivateKey_file(ctx,pkey,SSL_FILETYPE_ASN1)){
      SLang_verror(0,"Could not load private key");
      goto free;
    }

  if (1!=SSL_CTX_check_private_key(ctx)){
    SLang_verror(0,"Certificate and private keys do not match");
    goto free;
  }

  slctx = (SLsslctx_Type *)malloc(sizeof(SLsslctx_Type));
  slctx->is_server = 1;
  slctx->ctx = (void *)ctx;

  sslmmt = SLang_create_mmt(SLsslctx_Type_Id, (VOID_STAR) slctx);

  if (0!=SLang_push_mmt(sslmmt))
    SLang_free_mmt(sslmmt);

 free:
  if (NULL!=pkey)
    SLang_free_slstring(pkey);
  if (NULL!=cert)
    SLang_free_slstring(cert);
}
开发者ID:amitschang,项目名称:slcrypto,代码行数:62,代码来源:crypto-module.c

示例6: SSL_CTX_new

/*
 * Create a new TLS_CONTEXT instance.
 *  Returns: Pointer to TLS_CONTEXT instance on success
 *           NULL on failure;
 */
TLS_CONTEXT *new_tls_context(const char *ca_certfile, const char *ca_certdir,
                             const char *certfile, const char *keyfile,
                             CRYPTO_PEM_PASSWD_CB *pem_callback,
                             const void *pem_userdata, const char *dhfile,
                             bool verify_peer)
{
   TLS_CONTEXT *ctx;
   BIO *bio;
   DH *dh;

   ctx = (TLS_CONTEXT *)malloc(sizeof(TLS_CONTEXT));

   /* Allocate our OpenSSL TLSv1 Context */
   ctx->openssl = SSL_CTX_new(TLSv1_method());

   if (!ctx->openssl) {
      openssl_post_errors(M_FATAL, _("Error initializing SSL context"));
      goto err;
   }

   /* Set up pem encryption callback */
   if (pem_callback) {
      ctx->pem_callback = pem_callback;
      ctx->pem_userdata = pem_userdata;
   } else {
      ctx->pem_callback = crypto_default_pem_callback;
      ctx->pem_userdata = NULL;
   }
   SSL_CTX_set_default_passwd_cb(ctx->openssl, tls_pem_callback_dispatch);
   SSL_CTX_set_default_passwd_cb_userdata(ctx->openssl, (void *) ctx);

   /*
    * Set certificate verification paths. This requires that at least one
    * value be non-NULL
    */
   if (ca_certfile || ca_certdir) {
      if (!SSL_CTX_load_verify_locations(ctx->openssl, ca_certfile, ca_certdir)) {
         openssl_post_errors(M_FATAL, _("Error loading certificate verification stores"));
         goto err;
      }
   } else if (verify_peer) {
      /* At least one CA is required for peer verification */
      Jmsg0(NULL, M_ERROR, 0, _("Either a certificate file or a directory must be"
                         " specified as a verification store\n"));
      goto err;
   }

   /*
    * Load our certificate file, if available. This file may also contain a
    * private key, though this usage is somewhat unusual.
    */
   if (certfile) {
      if (!SSL_CTX_use_certificate_chain_file(ctx->openssl, certfile)) {
         openssl_post_errors(M_FATAL, _("Error loading certificate file"));
         goto err;
      }
   }

   /* Load our private key. */
   if (keyfile) {
      if (!SSL_CTX_use_PrivateKey_file(ctx->openssl, keyfile, SSL_FILETYPE_PEM)) {
         openssl_post_errors(M_FATAL, _("Error loading private key"));
         goto err;
      }
   }

   /* Load Diffie-Hellman Parameters. */
   if (dhfile) {
      if (!(bio = BIO_new_file(dhfile, "r"))) {
         openssl_post_errors(M_FATAL, _("Unable to open DH parameters file"));
         goto err;
      }
      dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
      BIO_free(bio);
      if (!dh) {
         openssl_post_errors(M_FATAL, _("Unable to load DH parameters from specified file"));
         goto err;
      }
      if (!SSL_CTX_set_tmp_dh(ctx->openssl, dh)) {
         openssl_post_errors(M_FATAL, _("Failed to set TLS Diffie-Hellman parameters"));
         DH_free(dh);
         goto err;
      }
      /* Enable Single-Use DH for Ephemeral Keying */
      SSL_CTX_set_options(ctx->openssl, SSL_OP_SINGLE_DH_USE);
   }

   if (SSL_CTX_set_cipher_list(ctx->openssl, TLS_DEFAULT_CIPHERS) != 1) {
      Jmsg0(NULL, M_ERROR, 0,
             _("Error setting cipher list, no valid ciphers available\n"));
      goto err;
   }

   /* Verify Peer Certificate */
   if (verify_peer) {
//.........这里部分代码省略.........
开发者ID:eneuhauss,项目名称:bareos,代码行数:101,代码来源:tls.c

示例7: MakeSSL_CTX

extern	SSL_CTX	*
MakeSSL_CTX(
	char	*key,
	char	*cert,
	char	*cafile,
	char	*capath,
	char	*ciphers)
{
	SSL_CTX *ctx = NULL;
	int	 mode = SSL_VERIFY_NONE;

	if ((ctx = SSL_CTX_new(SSLv23_method())) == NULL){
		SSL_Error(_d("SSL_CTX_new failure:\n %s\n"), GetSSLErrorString());
		return NULL;
	}

	SSL_CTX_set_default_passwd_cb(ctx, passphrase_callback);
	SSL_CTX_set_default_passwd_cb_userdata(ctx, (void*)ASKPASS_PROMPT);

	if (!SSL_CTX_set_cipher_list(ctx, ciphers)){
		SSL_Error(_d("SSL_CTX_set_cipher_list(%s) failure:\n %s\n"),
				ciphers, GetSSLErrorString());
		SSL_CTX_free(ctx);
		return NULL;
	}

	mode = SSL_VERIFY_PEER;
	mode |= SSL_VERIFY_CLIENT_ONCE;
	SSL_CTX_set_verify(ctx, mode, RemoteVerifyCallBack);
	SSL_CTX_set_options(ctx, SSL_OP_ALL);

	if ((cafile == NULL) && (capath == NULL)){
		if (!SSL_CTX_set_default_verify_paths(ctx)){
			SSL_Error(_d("SSL_CTX_set_default_verify_paths error:\n %s\n"),
					GetSSLErrorString());
		}
	}
	else if (!SSL_CTX_load_verify_locations(ctx, cafile, capath)){
		if (cafile == NULL) cafile = capath;
		SSL_Error(_d("SSL_CTX_load_verify_locations(%s)\n"), cafile);
		SSL_CTX_free(ctx);
		return NULL;
	}

	if (cert != NULL){
		if (IsPKCS12(cert)){
			if (LoadPKCS12(ctx, cert)){
				return ctx;
			}
			else {
				SSL_CTX_free(ctx);
				return NULL; 
			}
		}
		else {
			if (SSL_CTX_use_certificate_file_with_check(ctx, cert, SSL_FILETYPE_PEM) <= 0){
				SSL_Error(_d("SSL_CTX_use_certificate_file(%s) failure:\n %s\n"),
						cert, GetSSLErrorString());
				SSL_CTX_free(ctx);
				return NULL;
			}
			if (key == NULL) key = cert;
			for (;;){ 
				if (SSL_CTX_use_PrivateKey_file(ctx, key, SSL_FILETYPE_PEM) <= 0){
					int err_reason;
					err_reason = ERR_GET_REASON(ERR_peek_error());
					SSL_Error(_d("SSL_CTX_use_PrivateKey_file(%s) failure:\n %s\n"),
							key, GetSSLErrorString());
					if (err_reason == PEM_R_BAD_DECRYPT ||
						err_reason == EVP_R_BAD_DECRYPT) continue;
					SSL_CTX_free(ctx);
					return NULL;
				}
				break;
			}
			if (!SSL_CTX_check_private_key(ctx)){
				SSL_Error(_d("SSL_CTX_check_private_key failure:\n %s\n"),
						GetSSLErrorString());
				SSL_CTX_free(ctx);
				return NULL;
			}
		}
	} else {
		SSL_Error(_d("Please specify certificate file"));
		return NULL;
	}

	return ctx;
}
开发者ID:authorNari,项目名称:panda,代码行数:89,代码来源:net.c

示例8: pCtx

SslContext_t::SslContext_t (bool is_server, const string &privkeyfile, const string &certchainfile):
    pCtx (NULL),
    PrivateKey (NULL),
    Certificate (NULL)
{
    /* TODO: the usage of the specified private-key and cert-chain filenames only applies to
     * client-side connections at this point. Server connections currently use the default materials.
     * That needs to be fixed asap.
     * Also, in this implementation, server-side connections use statically defined X-509 defaults.
     * One thing I'm really not clear on is whether or not you have to explicitly free X509 and EVP_PKEY
     * objects when we call our destructor, or whether just calling SSL_CTX_free is enough.
     */

    if (!bLibraryInitialized) {
        bLibraryInitialized = true;
        SSL_library_init();
        OpenSSL_add_ssl_algorithms();
        OpenSSL_add_all_algorithms();
        SSL_load_error_strings();
        ERR_load_crypto_strings();

        InitializeDefaultCredentials();
    }

    bIsServer = is_server;
    pCtx = SSL_CTX_new (is_server ? SSLv23_server_method() : SSLv23_client_method());
    if (!pCtx)
        throw std::runtime_error ("no SSL context");

    SSL_CTX_set_options (pCtx, SSL_OP_ALL);
    //SSL_CTX_set_options (pCtx, (SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3));

    if (is_server) {
        // The SSL_CTX calls here do NOT allocate memory.
        int e;
        if (privkeyfile.length() > 0)
            e = SSL_CTX_use_PrivateKey_file (pCtx, privkeyfile.c_str(), SSL_FILETYPE_PEM);
        else
            e = SSL_CTX_use_PrivateKey (pCtx, DefaultPrivateKey);
        assert (e > 0);
        if (certchainfile.length() > 0)
            e = SSL_CTX_use_certificate_chain_file (pCtx, certchainfile.c_str());
        else
            e = SSL_CTX_use_certificate (pCtx, DefaultCertificate);
        assert (e > 0);
    }

    SSL_CTX_set_cipher_list (pCtx, "ALL:!ADH:!LOW:!EXP:!DES-CBC3-SHA:@STRENGTH");

    if (is_server) {
        SSL_CTX_sess_set_cache_size (pCtx, 128);
        SSL_CTX_set_session_id_context (pCtx, (unsigned char*)"eventmachine", 12);
    }
    else {
        int e;
        if (privkeyfile.length() > 0) {
            e = SSL_CTX_use_PrivateKey_file (pCtx, privkeyfile.c_str(), SSL_FILETYPE_PEM);
            assert (e > 0);
        }
        if (certchainfile.length() > 0) {
            e = SSL_CTX_use_certificate_chain_file (pCtx, certchainfile.c_str());
            assert (e > 0);
        }
    }
}
开发者ID:saimonmoore,项目名称:merb-sample-app-on-passenger,代码行数:65,代码来源:ssl.cpp

示例9: tport_ws_init_primary_secure

static int tport_ws_init_primary_secure(tport_primary_t *pri,
				 tp_name_t tpn[1],
				 su_addrinfo_t *ai,
				 tagi_t const *tags,
				 char const **return_culprit)
{
  tport_ws_primary_t *wspri = (tport_ws_primary_t *)pri;
  const char *cert = "/ssl.pem";
  const char *key = "/ssl.pem";
  char *homedir;
  char *tbf = NULL;
  su_home_t autohome[SU_HOME_AUTO_SIZE(1024)];
  char const *path = NULL;
  int ret = -1;

  su_home_auto(autohome, sizeof autohome);

  tl_gets(tags,
	  TPTAG_CERTIFICATE_REF(path),
	  TAG_END());

  if (!path) {
    homedir = getenv("HOME");
    if (!homedir)
      homedir = "";
    path = tbf = su_sprintf(autohome, "%s/.sip/auth", homedir);
  }

  if (path) {
    key  = su_sprintf(autohome, "%s/%s", path, "wss.key");
	if (access(key, R_OK) != 0) key = NULL;
	cert = su_sprintf(autohome, "%s/%s", path, "wss.crt");
	if (access(cert, R_OK) != 0) cert = NULL;
	if ( !key )  key  = su_sprintf(autohome, "%s/%s", path, "wss.pem");
	if ( !cert ) cert = su_sprintf(autohome, "%s/%s", path, "wss.pem");
	if (access(key, R_OK) != 0) key = NULL;
	if (access(cert, R_OK) != 0) cert = NULL;
  }

  init_ssl();

  //  OpenSSL_add_all_algorithms();   /* load & register cryptos */                                                                                       
  //  SSL_load_error_strings();     /* load all error messages */                                                                                         
  wspri->ssl_method = SSLv23_server_method();   /* create server instance */
  wspri->ssl_ctx = SSL_CTX_new((SSL_METHOD *)wspri->ssl_method);         /* create context */
  SSL_CTX_sess_set_remove_cb(wspri->ssl_ctx, NULL);
  wspri->ws_secure = 1;

  if ( !wspri->ssl_ctx ) goto done;

  /* set the local certificate from CertFile */
  SSL_CTX_use_certificate_file(wspri->ssl_ctx, cert, SSL_FILETYPE_PEM);
  /* set the private key from KeyFile */
  SSL_CTX_use_PrivateKey_file(wspri->ssl_ctx, key, SSL_FILETYPE_PEM);
  /* verify private key */
  if ( !SSL_CTX_check_private_key(wspri->ssl_ctx) ) {
	  goto done;
  }

  SSL_CTX_set_cipher_list(wspri->ssl_ctx, "HIGH:!DSS:[email protected]");

  ret = tport_ws_init_primary(pri, tpn, ai, tags, return_culprit);

 done:
  su_home_zap(autohome);
  return ret;
}
开发者ID:jrd,项目名称:FreeSWITCH,代码行数:67,代码来源:tport_type_ws.c

示例10: main

int main( int argc, char **argv ) {
    SSL_CTX *ctx = NULL;
    SSL *session = NULL;

    char *command = "HEAD / HTTP/1.0\r\n\r\n";
    
    int s;
    int status;

    /* We first need to establish what sort of
     * connection we know how to make. We can use one of
     * SSLv23_client_method(), SSLv2_client_method() and
     * SSLv3_client_method().
     */
    SSL_METHOD *meth = SSLv23_client_method();
    if (meth == NULL) { fprintf( stderr, "no method. :(\n" ); exit(1); }

    /* This enables all ciphers in SSLeay, these include:
     *   DES, RC4, IDEA, RC2, Blowfish,
     *   MD2, SHA, DSA.
     * See crypto/c_all.c
     */
    SSLeay_add_all_algorithms();

    /* Initialize the context. This is shared between SSL sessions
     * and can do FH caching.
     */
    ctx = SSL_CTX_new( meth );
    if ( ctx == NULL ) { fprintf( stderr, "no context. :(\n" ); exit(1); }

    /* Set up a callback for each state change so we can see what's
     * going on */
    SSL_CTX_set_info_callback(ctx,apps_ssl_info_callback);

    /* Set it up so tha we will connect to *any* site, regardless
     * of their certificate. */
    SSL_CTX_set_verify( ctx, SSL_VERIFY_NONE, my_dumb_callback );

    /* MACRO. Set's CTX options. Not sure. I think this enables bug
     * support hacks. */
    SSL_CTX_set_options(ctx,SSL_OP_ALL);

    /* Finally, we're all set so we can set up the session holder */
    session = SSL_new( ctx );
    if ( session == NULL ) { fprintf( stderr, "no session. :(\n" ); exit(1);}
    
    /* Make connection s.t. s is the appropriate fd */
    s = my_connect( (argc == 2) ? argv[1] : "bozo.mit.edu" , 443 );

    /* Set up the SSL side of the connection */
    SSL_set_fd( session, s );
    status = SSL_connect( session );
    /* Check the results. */
    switch (SSL_get_error(session,status)) {
    case SSL_ERROR_NONE:
	/* Everything worked :-) */
	break;
    case SSL_ERROR_SSL:
	fprintf( stderr, "ssl handshake failure\n" );
	ERR_print_errors_fp(stderr);
	goto byebye;
	break;

	/* These are for NON-BLOCKING I/O only! */
    case SSL_ERROR_WANT_READ:
    case SSL_ERROR_WANT_WRITE:
	fprintf( stderr, "want read/write. Use blocking?\n" );
	goto byebye;	break;
    case SSL_ERROR_WANT_CONNECT:
	fprintf( stderr, "want connect. sleep a while, try again." );
	goto byebye;    break;
	
    case SSL_ERROR_SYSCALL:
	perror("SSL_connect");
	goto byebye;    break;
    case SSL_ERROR_WANT_X509_LOOKUP:
	/* not used! */
	fprintf( stderr, "shouldn't be getting this.\n" );
	break;
    case SSL_ERROR_ZERO_RETURN:
	fprintf( stderr, "connection closed.\n" );
	goto byebye;
    }
    
    /* Send the request */
    SSL_write( session, command, strlen(command) );
    /* wait a second for processing. */
    sleep(1);

    /* read! :) */
    while (1) {
	char readdata[1024];

	status = SSL_read( session, readdata, 1024 );
	if ( status == 0 ) break;
	if ( status <  0 ) { sleep(1); continue; }
	fwrite( readdata, 1, status, stdout );
    }


//.........这里部分代码省略.........
开发者ID:hexxellor,项目名称:mitzee,代码行数:101,代码来源:ssl-client.c

示例11: fetch_uri

/*
 * Fetches the resource denoted by |uri|.
 */
static void
fetch_uri(const struct URI *uri)
{
    spdylay_session_callbacks callbacks;
    int fd;
    SSL_CTX *ssl_ctx;
    SSL *ssl;
    struct Request req;
    struct Connection connection;
    int rv;
    nfds_t npollfds = 1;
    struct pollfd pollfds[1];
    uint16_t spdy_proto_version;

    request_init(&req, uri);

    setup_spdylay_callbacks(&callbacks);

    /* Establish connection and setup SSL */
    fd = connect_to(req.host, req.port);
    if (-1 == fd)
        abort ();
    ssl_ctx = SSL_CTX_new(SSLv23_client_method());
    if(ssl_ctx == NULL) {
        dief("SSL_CTX_new", ERR_error_string(ERR_get_error(), NULL));
    }
    init_ssl_ctx(ssl_ctx, &spdy_proto_version);
    ssl = SSL_new(ssl_ctx);
    if(ssl == NULL) {
        dief("SSL_new", ERR_error_string(ERR_get_error(), NULL));
    }
    /* To simplify the program, we perform SSL/TLS handshake in blocking
       I/O. */
    ssl_handshake(ssl, fd);

    connection.ssl = ssl;
    connection.want_io = IO_NONE;

    /* Here make file descriptor non-block */
    make_non_block(fd);
    set_tcp_nodelay(fd);

    spdylay_printf("[INFO] SPDY protocol version = %d\n", spdy_proto_version);
    rv = spdylay_session_client_new(&connection.session, spdy_proto_version,
                                    &callbacks, &connection);
    if(rv != 0) {
        diec("spdylay_session_client_new", rv);
    }

    /* Submit the HTTP request to the outbound queue. */
    submit_request(&connection, &req);

    pollfds[0].fd = fd;
    ctl_poll(pollfds, &connection);

    /* Event loop */
    while(spdylay_session_want_read(connection.session) ||
            spdylay_session_want_write(connection.session)) {
        int nfds = poll(pollfds, npollfds, -1);
        if(nfds == -1) {
            dief("poll", strerror(errno));
        }
        if(pollfds[0].revents & (POLLIN | POLLOUT)) {
            exec_io(&connection);
        }
        if((pollfds[0].revents & POLLHUP) || (pollfds[0].revents & POLLERR)) {
            die("Connection error");
        }
        ctl_poll(pollfds, &connection);
    }

    /* Resource cleanup */
    spdylay_session_del(connection.session);
    SSL_shutdown(ssl);
    SSL_free(ssl);
    SSL_CTX_free(ssl_ctx);
    shutdown(fd, SHUT_WR);
    MHD_socket_close_ (fd);
    request_free(&req);
}
开发者ID:PavanKulk,项目名称:httpserver,代码行数:83,代码来源:test_new_connection.c

示例12: janus_dtls_srtp_init

/* DTLS-SRTP initialization */
gint janus_dtls_srtp_init(const char *server_pem, const char *server_key, const char *password) {
	const char *crypto_lib = NULL;
#if JANUS_USE_OPENSSL_PRE_1_1_API
#if defined(LIBRESSL_VERSION_NUMBER)
	crypto_lib = "LibreSSL";
#else
	crypto_lib = "OpenSSL pre-1.1.0";
#endif
	/* First of all make OpenSSL thread safe (see note above on issue #316) */
	janus_dtls_locks = g_malloc0(sizeof(*janus_dtls_locks) * CRYPTO_num_locks());
	int l=0;
	for(l = 0; l < CRYPTO_num_locks(); l++) {
		janus_mutex_init(&janus_dtls_locks[l]);
	}
	CRYPTO_THREADID_set_callback(janus_dtls_cb_openssl_threadid);
	CRYPTO_set_locking_callback(janus_dtls_cb_openssl_lock);
#else
	crypto_lib = "OpenSSL >= 1.1.0";
#endif
#ifdef HAVE_BORINGSSL
	crypto_lib = "BoringSSL";
#endif
	JANUS_LOG(LOG_INFO, "Crypto: %s\n", crypto_lib);
#ifndef HAVE_SRTP_AESGCM
	JANUS_LOG(LOG_WARN, "The libsrtp installation does not support AES-GCM profiles\n");
#endif

	/* Go on and create the DTLS context */
#if JANUS_USE_OPENSSL_PRE_1_1_API
	ssl_ctx = SSL_CTX_new(DTLSv1_method());
#else
	ssl_ctx = SSL_CTX_new(DTLS_method());
#endif
	if(!ssl_ctx) {
		JANUS_LOG(LOG_FATAL, "Ops, error creating DTLS context?\n");
		return -1;
	}
	SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, janus_dtls_verify_callback);
	SSL_CTX_set_tlsext_use_srtp(ssl_ctx,
#ifdef HAVE_SRTP_AESGCM
		"SRTP_AEAD_AES_256_GCM:SRTP_AEAD_AES_128_GCM:SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32");
#else
		"SRTP_AES128_CM_SHA1_80:SRTP_AES128_CM_SHA1_32");
#endif

	if(!server_pem && !server_key) {
		JANUS_LOG(LOG_WARN, "No cert/key specified, autogenerating some...\n");
		if(janus_dtls_generate_keys(&ssl_cert, &ssl_key) != 0) {
			JANUS_LOG(LOG_FATAL, "Error generating DTLS key/certificate\n");
			return -2;
		}
	} else if(!server_pem || !server_key) {
		JANUS_LOG(LOG_FATAL, "DTLS certificate and key must be specified\n");
		return -2;
	} else if(janus_dtls_load_keys(server_pem, server_key, password, &ssl_cert, &ssl_key) != 0) {
		return -3;
	}

	if(!SSL_CTX_use_certificate(ssl_ctx, ssl_cert)) {
		JANUS_LOG(LOG_FATAL, "Certificate error (%s)\n", ERR_reason_error_string(ERR_get_error()));
		return -4;
	}
	if(!SSL_CTX_use_PrivateKey(ssl_ctx, ssl_key)) {
		JANUS_LOG(LOG_FATAL, "Certificate key error (%s)\n", ERR_reason_error_string(ERR_get_error()));
		return -5;
	}
	if(!SSL_CTX_check_private_key(ssl_ctx)) {
		JANUS_LOG(LOG_FATAL, "Certificate check error (%s)\n", ERR_reason_error_string(ERR_get_error()));
		return -6;
	}
	SSL_CTX_set_read_ahead(ssl_ctx,1);

	unsigned int size;
	unsigned char fingerprint[EVP_MAX_MD_SIZE];
	if(X509_digest(ssl_cert, EVP_sha256(), (unsigned char *)fingerprint, &size) == 0) {
		JANUS_LOG(LOG_FATAL, "Error converting X509 structure (%s)\n", ERR_reason_error_string(ERR_get_error()));
		return -7;
	}
	char *lfp = (char *)&local_fingerprint;
	unsigned int i = 0;
	for(i = 0; i < size; i++) {
		g_snprintf(lfp, 4, "%.2X:", fingerprint[i]);
		lfp += 3;
	}
	*(lfp-1) = 0;
	JANUS_LOG(LOG_INFO, "Fingerprint of our certificate: %s\n", local_fingerprint);
	SSL_CTX_set_cipher_list(ssl_ctx, DTLS_CIPHERS);

	if(janus_dtls_bio_filter_init() < 0) {
		JANUS_LOG(LOG_FATAL, "Error initializing BIO filter\n");
		return -8;
	}

	/* Initialize libsrtp */
	if(srtp_init() != srtp_err_status_ok) {
		JANUS_LOG(LOG_FATAL, "Ops, error setting up libsrtp?\n");
		return 5;
	}
	return 0;
//.........这里部分代码省略.........
开发者ID:BladeSmithJohn,项目名称:janus-gateway,代码行数:101,代码来源:dtls.c

示例13: main


//.........这里部分代码省略.........
			use_tcp = 1;
			break;
		case 'S':
			use_secure = 1;
			break;
		case 'i':
		{
			char* fn = find_config_file(optarg,1);
			if(!fn) {
				fprintf(stderr,"ERROR: file %s not found\n",optarg);
				exit(-1);
			}
			strcpy(cert_file,fn);
			free(fn);
			break;
		}
		case 'k':
		{
			char* fn = find_config_file(optarg,1);
			if(!fn) {
				fprintf(stderr,"ERROR: file %s not found\n",optarg);
				exit(-1);
			}
			STRCPY(pkey_file,fn);
			free(fn);
			break;
		}
		default:
			fprintf(stderr, "%s\n", Usage);
			exit(1);
		}
	}

	if(port == 0) {
		if(use_secure)
			port = DEFAULT_STUN_TLS_PORT;
		else
			port = DEFAULT_STUN_PORT;
	}

	if (clmessage_length < (int) sizeof(message_info))
		clmessage_length = (int) sizeof(message_info);

	if (optind >= argc) {
		fprintf(stderr, "%s\n", Usage);
		exit(-1);
	}

	if (!c2c) {
		if (make_ioa_addr((const u08bits*) peer_address, peer_port, &peer_addr) < 0)
			return -1;
	}

	/* SSL Init ==>> */

	if(use_secure) {

		SSL_load_error_strings();
		OpenSSL_add_ssl_algorithms();

		if(use_tcp) {
			root_tls_ctx = SSL_CTX_new(TLSv1_client_method());
		} else {
#if !defined(BIO_CTRL_DGRAM_QUERY_MTU)
		  fprintf(stderr,"ERROR: DTLS is not supported.\n");
		  exit(-1);
#else
		  if(OPENSSL_VERSION_NUMBER < 0x10000000L) {
		  	TURN_LOG_FUNC(TURN_LOG_LEVEL_WARNING, "WARNING: OpenSSL version is rather old, DTLS may not be working correctly.\n");
		  }
		  root_tls_ctx = SSL_CTX_new(DTLSv1_client_method());
#endif
		}
		SSL_CTX_set_cipher_list(root_tls_ctx, "DEFAULT");

		if (!SSL_CTX_use_certificate_file(root_tls_ctx, cert_file,
			SSL_FILETYPE_PEM)) {
			TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "\nERROR: no certificate found!\n");
			exit(-1);
		}

		if (!SSL_CTX_use_PrivateKey_file(root_tls_ctx, pkey_file,
						SSL_FILETYPE_PEM)) {
			TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "\nERROR: no private key found!\n");
			exit(-1);
		}

		if (!SSL_CTX_check_private_key(root_tls_ctx)) {
			TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "\nERROR: invalid private key!\n");
			exit(-1);
		}

		SSL_CTX_set_verify_depth(root_tls_ctx, 2);
		SSL_CTX_set_read_ahead(root_tls_ctx, 1);
	}

	start_mclient(argv[optind], port, ifname, local_addr, messagenumber, mclient);

	return 0;
}
开发者ID:arnaudcoquelet,项目名称:oss_core,代码行数:101,代码来源:mainuclient.c

示例14: main


//.........这里部分代码省略.........
    lua_register(_L, "sendfile", lua_sendfile);
    lua_register(_L, "header", lua_header);
    lua_register(_L, "clear_header", lua_clear_header);
    lua_register(_L, "__end", lua_end);
    lua_register(_L, "die", lua_die);
    lua_register(_L, "flush", lua_flush);
    lua_register(_L, "read_request_body", lua_read_request_body);
    lua_register(_L, "get_boundary", lua_f_get_boundary);
    lua_register(_L, "check_timeout", lua_check_timeout);
    lua_register(_L, "is_websocket", lua_f_is_websocket);
    lua_register(_L, "upgrade_to_websocket", lua_f_upgrade_to_websocket);
    lua_register(_L, "websocket_send", lua_f_websocket_send);
    lua_register(_L, "check_websocket_close", lua_f_check_websocket_close);

    lua_register(_L, "router", lua_f_router);

    lua_register(_L, "random_string", lua_f_random_string);
    lua_register(_L, "file_exists", lua_f_file_exists);
    lua_register(_L, "readfile", lua_f_readfile);
    lua_register(_L, "filemtime", lua_f_filemtime);

    lua_register(_L, "cache_set", lua_f_cache_set);
    lua_register(_L, "cache_get", lua_f_cache_get);
    lua_register(_L, "cache_del", lua_f_cache_del);

    luaopen_fastlz(_L);
    luaopen_coevent(_L);
    luaopen_libfs(_L);
    luaopen_string_utils(_L);
    luaopen_i18n(_L);
    luaopen_crypto(_L);

    lua_pop(_L, 1);

    sprintf(tbuf_4096,
            "package.path = '%slua-libs/?.lua;' .. package.path package.cpath = '%slua-libs/?.so;' .. package.cpath", cwd, cwd);
    luaL_dostring(_L, tbuf_4096);

    luaL_dostring(_L, ""
                  "if not CODE_CACHE_TTL then CODE_CACHE_TTL = 60 end " \
                  "startloop = nil __CodeCache = {{},{}} __CodeCacheC = {false,false} "
                 );

    if(getarg("accesslog")) {
        ACCESS_LOG = open_log(getarg("accesslog"), 40960);

        if(!ACCESS_LOG) {
            LOGF(ERR, "Couldn't open access log file: %s", getarg("accesslog"));
        }
    }

    if(getarg("ssl-bind") && getarg("ssl-cert") && getarg("ssl-key")) {
        ssl_ctx = SSL_CTX_new(SSLv23_server_method());

        if(!ssl_ctx) {
            LOGF(ERR, "SSL_CTX_new Failed");
            exit(1);
        }

        if(SSL_CTX_use_certificate_file(ssl_ctx, getarg("ssl-cert"), SSL_FILETYPE_PEM) != 1) {
            SSL_CTX_free(ssl_ctx);
            LOGF(ERR, "SSL_CTX_use_certificate_file");
            exit(1);
        }

        if(SSL_CTX_use_PrivateKey_file(ssl_ctx, getarg("ssl-key"), SSL_FILETYPE_PEM) != 1) {
            SSL_CTX_free(ssl_ctx);
            LOGF(ERR, "SSL_CTX_use_PrivateKey_file");
            exit(1);
        }

        SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL);

        if(getarg("ssl-ca")) {
            ssl_epd_idx = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL);

            if(ssl_epd_idx == -1) {
                LOGF(ERR, "SSL_get_ex_new_index Failed");
                exit(1);
            }

            if(SSL_CTX_load_verify_locations(ssl_ctx, getarg("ssl-ca"), NULL) != 1) {
                SSL_CTX_free(ssl_ctx);
                LOGF(ERR, "SSL_CTX_load_verify_locations");
                exit(1);

            } else {
                SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback);
                SSL_CTX_set_verify_depth(ssl_ctx, 4);

            }
        }
    }

    _shm_serv_status = shm_malloc(sizeof(serv_status_t));
    bzero(_shm_serv_status->p, sizeof(serv_status_t));

    attach_on_exit(on_master_exit_handler);
    return merry_start(argc, argv, help, master_main, on_master_exit_handler, worker_main, 0);
}
开发者ID:MarkTseng,项目名称:alilua,代码行数:101,代码来源:main.c

示例15: TLSClientInitialize

/**
 * @warning Make sure you've called CryptoInitialize() first!
 */
bool TLSClientInitialize()
{
    int ret;
    static bool is_initialised = false;

    if (is_initialised)
    {
        return true;
    }

    if (!TLSGenericInitialize())
    {
        return false;
    }

    SSLCLIENTCONTEXT = SSL_CTX_new(SSLv23_client_method());
    if (SSLCLIENTCONTEXT == NULL)
    {
        Log(LOG_LEVEL_ERR, "SSL_CTX_new: %s",
            ERR_reason_error_string(ERR_get_error()));
        goto err1;
    }

    TLSSetDefaultOptions(SSLCLIENTCONTEXT);

    if (PRIVKEY == NULL || PUBKEY == NULL)
    {
        Log(CryptoGetMissingKeyLogLevel(),
            "No public/private key pair is loaded, trying to reload");
        LoadSecretKeys();
        if (PRIVKEY == NULL || PUBKEY == NULL)
        {
            Log(CryptoGetMissingKeyLogLevel(),
                "No public/private key pair found");
            goto err2;
        }
    }

    /* Create cert into memory and load it into SSL context. */
    SSLCLIENTCERT = TLSGenerateCertFromPrivKey(PRIVKEY);
    if (SSLCLIENTCERT == NULL)
    {
        Log(LOG_LEVEL_ERR,
            "Failed to generate in-memory-certificate from private key");
        goto err2;
    }

    SSL_CTX_use_certificate(SSLCLIENTCONTEXT, SSLCLIENTCERT);

    ret = SSL_CTX_use_RSAPrivateKey(SSLCLIENTCONTEXT, PRIVKEY);
    if (ret != 1)
    {
        Log(LOG_LEVEL_ERR, "Failed to use RSA private key: %s",
            ERR_reason_error_string(ERR_get_error()));
        goto err3;
    }

    /* Verify cert consistency. */
    ret = SSL_CTX_check_private_key(SSLCLIENTCONTEXT);
    if (ret != 1)
    {
        Log(LOG_LEVEL_ERR, "Inconsistent key and TLS cert: %s",
            ERR_reason_error_string(ERR_get_error()));
        goto err3;
    }

    is_initialised = true;
    return true;

  err3:
    X509_free(SSLCLIENTCERT);
    SSLCLIENTCERT = NULL;
  err2:
    SSL_CTX_free(SSLCLIENTCONTEXT);
    SSLCLIENTCONTEXT = NULL;
  err1:
    return false;
}
开发者ID:lra,项目名称:core,代码行数:81,代码来源:tls_client.c


注:本文中的SSL_CTX_new函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。