public async Task <ServerCredentials> Generate(string type, string configuration)
        {
            var sslConfiguration = JsonSerializerHelper.Deserialize <SSLConfiguration>(configuration);
            var cacert           = File.ReadAllText(sslConfiguration.CAFile);
            var servercert       = File.ReadAllText(sslConfiguration.ServerFile);
            var serverkey        = File.ReadAllText(sslConfiguration.KeyFile);
            var keypair          = new KeyCertificatePair(servercert, serverkey);

            SslClientCertificateRequestType clientStrategy;

            switch (sslConfiguration.ClientStrategy)
            {
            case 1:
                clientStrategy = SslClientCertificateRequestType.DontRequest;
                break;

            default:
                clientStrategy = SslClientCertificateRequestType.RequestAndRequireAndVerify;
                break;
            }

            var sslCredentials = new SslServerCredentials(new List <KeyCertificatePair>()
            {
                keypair
            }, cacert, clientStrategy);

            return(await Task.FromResult(sslCredentials));
        }
示例#2
0
        public ChatServiceClient()
        {
            // Locate required files and set true to enable SSL
            var secure = false;

            if (secure)
            {
                // create secure channel
                var serverCACert = File.ReadAllText(@"C:\localhost_server.crt");
                var clientCert   = File.ReadAllText(@"C:\localhost_client.crt");
                var clientKey    = File.ReadAllText(@"C:\localhost_clientkey.pem");
                var keyPair      = new KeyCertificatePair(clientCert, clientKey);
                var credentials  = new SslCredentials(serverCACert, keyPair);

                // Client authentication is an option. You can remove it as follows if you only need SSL.
                //var credentials = new SslCredentials(serverCACert);

                m_client = new Chat.ChatClient(
                    new Channel("localhost", 50052, credentials));
            }
            else
            {
                // create insecure channel
                m_client = new Chat.ChatClient(
                    new Channel("localhost", 50052, ChannelCredentials.Insecure));
            }
        }
示例#3
0
        private bool SetupSsl(string caCertLocation, string certLocation, string clientKeyLocation)
        {
            try
            {
                if (string.IsNullOrEmpty(caCertLocation))
                {
                    throw new ArgumentException("message", nameof(caCertLocation));
                }

                if (string.IsNullOrEmpty(certLocation))
                {
                    throw new ArgumentException("message", nameof(certLocation));
                }

                if (string.IsNullOrEmpty(clientKeyLocation))
                {
                    throw new ArgumentException("message", nameof(clientKeyLocation));
                }

                _caCert = File.ReadAllText(caCertLocation);
                _cert   = File.ReadAllText(certLocation);
                _key    = File.ReadAllText(clientKeyLocation);

                _keyPair     = new KeyCertificatePair(_cert, _key);
                _credentials = new SslCredentials(_caCert, _keyPair);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
示例#4
0
        public static void Main(string[] args)
        {
            const int port   = 9000;
            var       cacert = File.ReadAllText("Keys/ca.crt");
            var       cert   = File.ReadAllText("Keys/client.crt");
            var       key    = File.ReadAllText("Keys/client.key");

            var keypair  = new KeyCertificatePair(cert, key);
            var sslCreds = new SslCredentials(cacert, keypair);

            var channel = new Channel("Alexiss-MacBook-Pro.local", port, sslCreds);

            var client = new UserServiceClient(channel);

            Console.WriteLine("--- UNARY CALL ---------------------");
            GetByUserIdAsync(client).Wait();
            Console.WriteLine("------------------------------------");
            Console.WriteLine("--- SERVER STREAMING CALL ----------");
            GetAllAsync(client).Wait();
            Console.WriteLine("------------------------------------");
            Console.WriteLine("--- CLIENT STREAMING CALL ----------");
            AddImageAsync(client).Wait();
            Console.WriteLine("------------------------------------");
            Console.WriteLine("--- BIDIRECTIONAL STREAMING CALL ---");
            SaveAllAsync(client).Wait();
            Console.WriteLine("------------------------------------");
        }
示例#5
0
        static void Main(string[] args)
        {
            Environment.SetEnvironmentVariable("GRPC_DNS_RESOLVER",
                                               "native");
            var option = 3; // int.Parse(args[0]);

            var            cacert  = File.ReadAllText(@"certs/ca.crt");
            var            cert    = File.ReadAllText(@"certs/client.crt");
            var            key     = File.ReadAllText(@"certs/client.key");
            var            keypair = new KeyCertificatePair(cert, key);
            SslCredentials creds   = new SslCredentials(cacert, keypair);
            var            channel = new Channel("DESKTOP-AQ2TIF3", Port, creds);
            var            client  = new EmployeeServiceClient(channel);

            switch (option)
            {
            case 1:
                SendMetadataAsync(client).Wait();
                break;

            case 2:
                GetByBadgeNumber(client).Wait();
                break;

            case 3:
                GetAll(client).Wait();
                break;

            case 4:
                AddPhoto(client).Wait();
                break;
            }
        }
示例#6
0
        static void Main(string[] args)
        {
            Console.WriteLine("Press any key to start...");
            Console.ReadKey();

            var cacert  = File.ReadAllText(CertPath + @"ca.crt");
            var cert    = File.ReadAllText(CertPath + @"client.crt");
            var key     = File.ReadAllText(CertPath + @"client.key");
            var keypair = new KeyCertificatePair(cert, key);
            var creds   = new SslCredentials(cacert, keypair);

            // The host value should be same with COMPUTERNAME in generate_crt_key.bat
            var channel = new Channel("localhost", Port, creds);
            var client  = new PingClient(new PingApi.PingApiClient(channel));

            // Test echo
            client.Ping("sender1", 10L);
            client.Ping("sender2", 100L);
            client.Ping("sender3", 1000L);
            client.Ping("sender4", 10000L);
            client.Ping("sender5", 100000L);
            client.Ping("sender6", 1000000L);

            channel.ShutdownAsync().Wait();
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
示例#7
0
        public static void Main(string[] args)
        {
            XmlConnector.Path = args.Length == 0 ? Directory.GetCurrentDirectory() : args[0];

            var cacert         = File.ReadAllText(@"/keys/ca.crt");
            var servercert     = File.ReadAllText(@"/keys/server.crt");
            var serverkey      = File.ReadAllText(@"/keys/server.key");
            var keypair        = new KeyCertificatePair(servercert, serverkey);
            var sslCredentials = new SslServerCredentials(new List <KeyCertificatePair>()
            {
                keypair
            }, cacert, false);


            var transaqConnectorImpl = new TransaqConnectorImpl();
            var server = new Server
            {
                Services = { TransaqConnector.BindService(transaqConnectorImpl) },
                Ports    = { new ServerPort("0.0.0.0", Port, sslCredentials) }
            };

            XmlConnector.Init(str =>
            {
                transaqConnectorImpl.OnMsg(str);
                return(str);
            });

            server.Start();

            Console.WriteLine("Greeter server listening on port " + Port);
            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();

            server.ShutdownAsync().Wait();
        }
示例#8
0
        public static void Main(string[] args)
        {
            var option = int.Parse(args[0]);

            var            cacert  = File.ReadAllText(@"ca.crt");
            var            cert    = File.ReadAllText(@"client.crt");
            var            key     = File.ReadAllText(@"client.key");
            var            keypair = new KeyCertificatePair(cert, key);
            SslCredentials creds   = new SslCredentials(cacert, keypair);
            var            channel = new Channel("DESKTOP-1UHNCG6", Port, creds);
            var            client  = new EmployeeServiceClient(channel);

            switch (option)
            {
            case 1:
                SendMetadataAsync(client).Wait();
                break;

            case 2:
                GetByBadgeNumber(client).Wait();
                break;

            case 3:
                GetAll(client).Wait();
                break;

            case 4:
                AddPhoto(client).Wait();
                break;

            case 5:
                SaveAll(client).Wait();
                break;
            }
        }
示例#9
0
        public static void Main(string[] args)
        {
            const int Port           = 9000;
            var       cacert         = File.ReadAllText(@"ca.crt");
            var       cert           = File.ReadAllText(@"server.crt");
            var       key            = File.ReadAllText(@"server.key");
            var       keypair        = new KeyCertificatePair(cert, key);
            var       sslCredentials = new SslServerCredentials(new List <KeyCertificatePair>()
            {
                keypair
            }, cacert, false);

            Server server = new Server
            {
                Services = { BindService(new EmployeeService()) },
                Ports    = { new ServerPort("0.0.0.0", Port, sslCredentials) }
            };

            server.Start();

            Console.WriteLine("Starting server on port " + Port);
            Console.WriteLine("Press any key to stop...");
            Console.ReadKey();

            server.ShutdownAsync().Wait();
        }
示例#10
0
        public async Task <ChannelCredentials> Generate(string type, string configuration)
        {
            var sslConfiguration = JsonSerializerHelper.Deserialize <SSLConfiguration>(configuration);
            var cacert           = File.ReadAllText(sslConfiguration.CAFile);

            SslClientCertificateRequestType clientStrategy;

            switch (sslConfiguration.ClientStrategy)
            {
            case 1:
                clientStrategy = SslClientCertificateRequestType.DontRequest;
                break;

            default:
                clientStrategy = SslClientCertificateRequestType.RequestAndRequireAndVerify;
                break;
            }

            SslCredentials sslCredentials;

            if (clientStrategy == SslClientCertificateRequestType.RequestAndRequireAndVerify)
            {
                var servercert = File.ReadAllText(sslConfiguration.ChannelFile);
                var serverkey  = File.ReadAllText(sslConfiguration.KeyFile);
                var keypair    = new KeyCertificatePair(servercert, serverkey);
                sslCredentials = new SslCredentials(cacert, keypair);
            }
            else
            {
                sslCredentials = new SslCredentials(cacert);
            }
            return(await Task.FromResult(sslCredentials));
        }
示例#11
0
        static void Main(string[] args)
        {
            const int port   = 9000;
            var       cacert = File.ReadAllText("Keys/ca.crt");
            var       cert   = File.ReadAllText("Keys/server.crt");
            var       key    = File.ReadAllText("Keys/server.key");

            var keypair  = new KeyCertificatePair(cert, key);
            var sslCreds = new SslServerCredentials(new List <KeyCertificatePair>
            {
                keypair
            }, cacert, false);

            Grpc.Core.Server server = new Grpc.Core.Server
            {
                Ports    = { new ServerPort("0.0.0.0", port, sslCreds) },
                Services = { BindService(new UsersService()) }
            };

            server.Start();

            Console.WriteLine("Starting server on port " + port);
            Console.WriteLine("Press any key to stop...");
            Console.ReadKey();
        }
示例#12
0
        public static void Main(string[] args)
        {
            var cacert         = File.ReadAllText(@"C:\Sertifika\ca.crt");
            var servercert     = File.ReadAllText(@"C:\Sertifika\server.crt");
            var serverkey      = File.ReadAllText(@"C:\Sertifika\server.key");
            var keypair        = new KeyCertificatePair(servercert, serverkey);
            var sslCredentials = new SslServerCredentials(new List <KeyCertificatePair>()
            {
                keypair
            }, cacert, false);


            Server server = new Server
            {
                Services = { Greeter.BindService(new GreeterImpl()) },
                Ports    = { new ServerPort("localhost", Port, sslCredentials) }
            };

            server.Start();

            Console.WriteLine("Greeter server listening on port " + Port);
            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();

            server.ShutdownAsync().Wait();
        }
示例#13
0
        public void Init()
        {
            var rootCert    = File.ReadAllText(TestCredentials.ClientCertAuthorityPath);
            var keyCertPair = new KeyCertificatePair(
                File.ReadAllText(TestCredentials.ServerCertChainPath),
                File.ReadAllText(TestCredentials.ServerPrivateKeyPath));

            var serverCredentials = new SslServerCredentials(new[] { keyCertPair }, rootCert, true);
            var clientCredentials = new SslCredentials(rootCert, keyCertPair);

            server = new Server
            {
                Services = { TestService.BindService(new TestServiceImpl()) },
                Ports    = { { Host, ServerPort.PickUnused, serverCredentials } }
            };
            server.Start();

            var options = new List <ChannelOption>
            {
                new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride)
            };

            channel = new Channel(Host, server.Ports.Single().BoundPort, clientCredentials, options);
            client  = new TestService.TestServiceClient(channel);
        }
示例#14
0
        static void Main(string[] args)
        {
            var cacert      = File.ReadAllText(@"..\certs\ca.crt");
            var cert        = File.ReadAllText(@"..\certs\server.crt");
            var key         = File.ReadAllText(@"..\certs\server.key");
            var keypair     = new KeyCertificatePair(cert, key);
            var credentials = new SslServerCredentials(new List <KeyCertificatePair>
            {
                keypair
            }, cacert, false);

            Server server = new Server
            {
                Services = { KnockKnock.KnockKnockService.BindService(new KnockKnockService()) },
                Ports    = { new ServerPort("0.0.0.0", Port, credentials) }
            };

            server.Start();

            Console.WriteLine("Knock Knock server listening on port " + Port);
            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();

            server.ShutdownAsync().Wait();
        }
        static ChannelCredentials CreateCredentials(bool mutualTls, bool useJwt)
        {
            var certsPath = Environment.GetEnvironmentVariable("CERTS_PATH");

            var caRoots = File.ReadAllText(Path.Combine(certsPath, "ca.pem"));
            ChannelCredentials channelCredentials;

            if (!mutualTls)
            {
                channelCredentials = new SslCredentials(caRoots);
            }
            else
            {
                var keyCertPair = new KeyCertificatePair(
                    File.ReadAllText(Path.Combine(certsPath, "client.pem")),
                    File.ReadAllText(Path.Combine(certsPath, "client.key")));
                channelCredentials = new SslCredentials(caRoots, keyCertPair);
            }

            if (useJwt)
            {
                var authInterceptor = new AsyncAuthInterceptor(async(context, metadata) =>
                {
                    metadata.Add(
                        new Metadata.Entry("authorization", "Bearer " + GenerateJwt()));
                });

                var metadataCredentials = CallCredentials.FromInterceptor(authInterceptor);
                channelCredentials = ChannelCredentials.Create(channelCredentials, metadataCredentials);
            }
            return(channelCredentials);
        }
        public ISender GetSender(ILoggerFactory loggerFactory, Configuration.SenderConfiguration senderConfiguration)
        {
            var logger = loggerFactory.CreateLogger <GrpcSenderFactory>();

            ChannelCredentials credentials;

            if (!string.IsNullOrEmpty(senderConfiguration.GrpcRootCertificate))
            {
                logger.LogDebug("Using TLS gRPC channel with data from the configuration.");

                KeyCertificatePair keypair = null;
                if (!string.IsNullOrEmpty(senderConfiguration.GrpcClientChain) &&
                    !string.IsNullOrEmpty(senderConfiguration.GrpcClientKey))
                {
                    var clientcert = File.ReadAllText(senderConfiguration.GrpcClientChain);
                    var clientkey  = File.ReadAllText(senderConfiguration.GrpcClientKey);
                    keypair = new KeyCertificatePair(clientcert, clientkey);
                }

                var rootcert = File.ReadAllText(senderConfiguration.GrpcRootCertificate);
                credentials = new SslCredentials(rootcert, keypair);
            }
            else
            {
                logger.LogDebug("Using insecure gRPC channel without credentials.");
                credentials = ChannelCredentials.Insecure;
            }

            logger.LogDebug("Using the gRPC Sender to send spans directly to the endpoint.");
            return(new GrpcSender(
                       StringOrDefault(senderConfiguration.GrpcTarget, GrpcSender.DefaultCollectorGrpcTarget),
                       credentials,
                       0 /* max packet size */));
        }
示例#17
0
        public static void Start(IConfigurationRoot config)
        {
            var builder = new ContainerBuilder();

            builder.RegisterInstance(config).As <IConfigurationRoot>();
            //builder.RegisterInstance(new DataContext(config)).As<IDataContext>();
            //builder.RegisterAssemblyTypes(typeof(IDataContext).GetTypeInfo().Assembly).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces();

            _container = builder.Build();
            var servercert     = File.ReadAllText(@"server.crt");
            var serverkey      = File.ReadAllText(@"server.key");
            var keypair        = new KeyCertificatePair(servercert, serverkey);
            var sslCredentials = new SslServerCredentials(new List <KeyCertificatePair>()
            {
                keypair
            });
            var healthService = new HealthServiceImpl();

            _server = new Grpc.Core.Server
            {
                Services = { MsgService.BindService(new MsgServiceImpl()), Grpc.Health.V1.Health.BindService(healthService) },
                Ports    = { new ServerPort("0.0.0.0", 9007, sslCredentials) }
            };
            _server.Start();
            healthService.SetStatus("Demo", Grpc.Health.V1.HealthCheckResponse.Types.ServingStatus.Serving);
            _server.ShutdownTask.Wait();
        }
示例#18
0
        /// <inheritdoc />
        public void Start(IEnumerable <ServerServiceDefinition> services)
        {
            _logger.LogTrace($"[Grpc Server Layer. {_identity}] Запускается Grpc Server с конфигурацией: Host:{_config.Host.Hostname}; Port: {_config.Host.Port}; SSL: {_config.Ssl != null}");

            var credentials = ServerCredentials.Insecure;

            if (_config.Ssl != null)
            {
                var cacert     = File.ReadAllText(Path.Combine(_config.Ssl.Path, _config.Ssl.CaCert));
                var servercert = File.ReadAllText(Path.Combine(_config.Ssl.Path, _config.Ssl.CertificateChain));
                var serverkey  = File.ReadAllText(Path.Combine(_config.Ssl.Path, _config.Ssl.PrivateKey));
                var keypair    = new KeyCertificatePair(servercert, serverkey);
                credentials = new SslServerCredentials(
                    new List <KeyCertificatePair> {
                    keypair
                },
                    cacert,
                    SslClientCertificateRequestType.DontRequest);
            }

            _server = new Server(new[] { new ChannelOption(ChannelOptions.SoReuseport, 0) })
            {
                Ports = { new ServerPort(_config.Host.Hostname, _config.Host.Port, credentials) },
            };

            foreach (var definition in services)
            {
                _server.Services.Add(definition);
                _logger.LogTrace($"[Grpc Server Layer. {_identity}] Добавляется конечная точка. {definition}");
            }

            _server.Start();
            _logger.LogTrace($"[Grpc Server Layer. {_identity}] Grpc Server запущен.");
        }
示例#19
0
        public static void Main(string[] args)
        {
            //Environment.SetEnvironmentVariable("GRPC_TRACE", "all");
            Environment.SetEnvironmentVariable("GRPC_VERBOSITY", "debug");
            GrpcEnvironment.SetLogger(new ConsoleLogger());

            //https://stackoverflow.com/questions/37714558/how-to-enable-server-side-ssl-for-grpc
            var cacert     = File.ReadAllText(@"C:\Users\ABOK078\Desktop\gRPC presentation\Grpc-Demo\cert\ca.crt");
            var servercert = File.ReadAllText(@"C:\Users\ABOK078\Desktop\gRPC presentation\Grpc-Demo\cert\server.crt");
            var serverkey  = File.ReadAllText(@"C:\Users\ABOK078\Desktop\gRPC presentation\Grpc-Demo\cert\server.key");
            var keypair    = new KeyCertificatePair(servercert, serverkey);

            var credentials = new SslServerCredentials(new[] { keypair }, cacert, true);

            Server server = new Server
            {
                Services = { MarketData.BindService(new RandomMarketDataService()) },
                //Ports = { new ServerPort("0.0.0.0", Port, ServerCredentials.Insecure) }
                Ports = { new ServerPort("0.0.0.0", Port, credentials) }
            };

            server.Start();

            Console.WriteLine("MarketData server listening on port " + Port);
            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();

            server.ShutdownAsync().Wait();
        }
示例#20
0
        public void InitClientAndServer(bool clientAddKeyCertPair,
                                        SslClientCertificateRequestType clientCertRequestType,
                                        VerifyPeerCallback verifyPeerCallback = null)
        {
            rootCert    = File.ReadAllText(TestCredentials.ClientCertAuthorityPath);
            keyCertPair = new KeyCertificatePair(
                File.ReadAllText(TestCredentials.ServerCertChainPath),
                File.ReadAllText(TestCredentials.ServerPrivateKeyPath));

            var serverCredentials = new SslServerCredentials(new[] { keyCertPair }, rootCert, clientCertRequestType);
            var clientCredentials = new SslCredentials(rootCert, clientAddKeyCertPair ? keyCertPair : null, verifyPeerCallback);

            // Disable SO_REUSEPORT to prevent https://github.com/grpc/grpc/issues/10755
            server = new Server(new[] { new ChannelOption(ChannelOptions.SoReuseport, 0) })
            {
                Services = { TestService.BindService(new SslCredentialsTestServiceImpl()) },
                Ports    = { { Host, ServerPort.PickUnused, serverCredentials } }
            };
            server.Start();

            var options = new List <ChannelOption>
            {
                new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride)
            };

            channel = new Channel(Host, server.Ports.Single().BoundPort, clientCredentials, options);
            client  = new TestService.TestServiceClient(channel);
        }
示例#21
0
        static void Main(string[] args)
        {
            const int Port   = 9000;
            var       cacert = File.ReadAllText(@"certs/ca.crt");
            var       cert   = File.ReadAllText(@"certs/server.crt");
            var       key    = File.ReadAllText(@"certs/server.key");

            var keypair = new KeyCertificatePair(cert, key);

            var sslCredentials = new SslServerCredentials(new List <KeyCertificatePair>()
            {
                keypair
            }, cacert, false);

            Server server = new Server
            {
                Ports =   //new ServerPort("0.0.0.0", Port, sslCredentials),
                {
                    new ServerPort("[::]", Port, sslCredentials)
                }                                              // listening on IP6 port 9000
            };

            server.Services.Add(BindService(new EmployeeService()));
            foreach (var service in server.Services)
            {
                Console.WriteLine($"Service: {service}");
            }
            server.Start();

            Console.WriteLine($"Starting Server on port {Port}");
            Console.WriteLine("Press any key to stop...");
            Console.ReadKey();

            server.ShutdownAsync().Wait();
        }
示例#22
0
        public static SslServerCredentials CreateTestServerCredentials()
        {
            var keyCertPair = new KeyCertificatePair(
                File.ReadAllText(ServerCertChainPath),
                File.ReadAllText(ServerPrivateKeyPath));

            return(new SslServerCredentials(ImmutableList.Create(keyCertPair)));
        }
示例#23
0
        public static SslServerCredentials CreateSslServerCredentials()
        {
            var keyCertPair = new KeyCertificatePair(
                File.ReadAllText(ServerCertChainPath),
                File.ReadAllText(ServerPrivateKeyPath));

            return(new SslServerCredentials(new[] { keyCertPair }));
        }
        /// <summary>
        /// 使用ssl加密启动服务
        /// 建议使用RSA  密钥长度可以为1024,2048 或者 4096 bits
        /// 可以使用sslgen.cmd每次生成不同的密钥
        /// </summary>
        /// <param name="serverCertFile">共用证书</param>
        /// <param name="privateKeyFile">私钥</param>
        /// <param name="exceptionHandler"></param>
        /// <returns></returns>
        public bool StartWithSsl(string serverCertFile = "server.crt", string privateKeyFile = "server.key", Action <Exception> exceptionHandler = null)
        {
            try
            {
                ////Server可以服务多个services,绑定多个端口
                //Server server = new Server(options)
                //{
                //    //可以注册多个service
                //    Services = { Greeter.BindService(new GreeterServiceImpl()), },
                //    //可以注册多个端口
                //    //0.0.0.0监听在本机的所有IP地址
                //    Ports = { new ServerPort(IPAddress.Any.ToString()/*0.0.0.0*/, Port, ServerCredentials.Insecure/*没有安全验证*/) },

                //};

                //Server可以定义多个服务,绑定多个端口
                _server = new Server(GrpcOptions);

                //添加多个服务
                foreach (var serviceItem in _serviceList)
                {
                    //服务实现抛出异常不会挂掉服务器,客户端捕获如下异常信息:Status(StatusCode=Unknown, Detail="Exception was thrown by handler.")
                    _server.Services.Add(serviceItem);
                }

                #region ssl加密

                //证书链PEM encoded certificate chain  包含公钥 有效期 签发者等信息,但不包含私钥
                string serverCert = File.ReadAllText(serverCertFile, Encoding.UTF8);
                //私钥PEM encoded private key  不能公开,只有服务器上有
                string privateKey = File.ReadAllText(privateKeyFile, Encoding.UTF8);


                KeyCertificatePair keyPair = new KeyCertificatePair(serverCert, privateKey);

                SslServerCredentials sslCredentials = new SslServerCredentials(new List <KeyCertificatePair>()
                {
                    keyPair
                });

                #endregion

                //添加多个监听端口
                //0.0.0.0表示监听本机所有ip地址, 没有安全验证
                //string ipAny = IPAddress.Any.ToString();
                //ssl证书
                _server.Ports.Add(this._bindIp, this._serverPort, sslCredentials);

                _server.Start();

                return(true);
            }
            catch (Exception e)
            {
                exceptionHandler?.Invoke(e);
                return(false);
            }
        }
示例#25
0
        /// <summary>
        /// Вспомогательный метод генерации серверных кредов из сертификата
        /// </summary>
        private ServerCredentials BuildSSLCredentials()
        {
            var cert = File.ReadAllText("cert\\server.crt");
            var key  = File.ReadAllText("cert\\server.key");

            var keyCertPair = new KeyCertificatePair(cert, key);

            return(new SslServerCredentials(new[] { keyCertPair }));
        }
示例#26
0
        public static KeyCertificatePair GenerateKeyCertificatePair()
        {
            var rsaKeyPair  = GenerateRsaKeyPair();
            var certificate = GenerateCertificate(new X509Name(X509NamePrefix + GrpcConstants.DefaultTlsCommonName),
                                                  new X509Name(X509NamePrefix + GrpcConstants.DefaultTlsCommonName), rsaKeyPair.Private, rsaKeyPair.Public);

            var keyCertificatePair = new KeyCertificatePair(ObjectToPem(certificate), ObjectToPem(rsaKeyPair.Private));

            return(keyCertificatePair);
        }
示例#27
0
        public SslCredentials GetSslClientCredentials()
        {
            var caCert      = File.ReadAllText(Path.Combine(Defines.CertFolderPath, Defines.CaCertificateName));
            var cert        = File.ReadAllText(Path.Combine(Defines.CertFolderPath, Defines.ClientCertificateName));
            var key         = File.ReadAllText(Path.Combine(Defines.CertFolderPath, Defines.ClientCertificateKeyName));
            var keyPair     = new KeyCertificatePair(cert, key);
            var credentials = new SslCredentials(caCert, keyPair);

            return(credentials);
        }
示例#28
0
        public void AddPort(string host, int port, string sslPublicKey, string sslPrivateKey)
        {
            var keyPair        = new KeyCertificatePair(sslPublicKey, sslPrivateKey);
            var sslCredentials = new SslServerCredentials(new List <KeyCertificatePair> {
                keyPair
            });
            var serverPort = new ServerPort(host, port, sslCredentials);

            Ports.Add(serverPort);
        }
示例#29
0
        private void CreateClientKeyCertificatePair()
        {
            var commonCertifName = "CN=" + GrpcConstants.DefaultTlsCommonName;

            var rsaKeyPair        = TlsHelper.GenerateRsaKeyPair();
            var clientCertificate = TlsHelper.GenerateCertificate(new X509Name(commonCertifName),
                                                                  new X509Name(commonCertifName), rsaKeyPair.Private, rsaKeyPair.Public);

            _clientKeyCertificatePair = new KeyCertificatePair(TlsHelper.ObjectToPem(clientCertificate), TlsHelper.ObjectToPem(rsaKeyPair.Private));
        }
 public static ChannelCredentialsSafeHandle CreateSslCredentials(string pemRootCerts, KeyCertificatePair keyCertPair)
 {
     if (keyCertPair != null)
     {
         return grpcsharp_ssl_credentials_create(pemRootCerts, keyCertPair.CertificateChain, keyCertPair.PrivateKey);
     }
     else
     {
         return grpcsharp_ssl_credentials_create(pemRootCerts, null, null);
     }
 }
        static SslCredentials GetSslCredentials()
        {
            var CERT_PATH = Path.Combine(Environment.CurrentDirectory, "Certs");
            var cacert    = File.ReadAllText(Path.Combine(CERT_PATH, "ca.crt"));
            var cert      = File.ReadAllText(Path.Combine(CERT_PATH, "client.crt"));
            var key       = File.ReadAllText(Path.Combine(CERT_PATH, "client.key"));

            var keyPair = new KeyCertificatePair(cert, key);
            var Creds   = new SslCredentials(cacert, keyPair);

            return(Creds);
        }