public static ChannelCredentials CreateChannelCredentials( bool useTls, [CanBeNull] string clientCertificate = null) { if (!useTls) { _logger.LogDebug("Using insecure channel credentials"); return(ChannelCredentials.Insecure); } string rootCertificatesAsPem = CertificateUtils.GetUserRootCertificatesInPemFormat(); KeyCertificatePair sslClientCertificate = null; if (!string.IsNullOrEmpty(clientCertificate)) { KeyPair keyPair = CertificateUtils.FindKeyCertificatePairFromStore( clientCertificate, new[] { X509FindType.FindBySubjectDistinguishedName, X509FindType.FindByThumbprint, X509FindType.FindBySubjectName }, StoreName.My, StoreLocation.CurrentUser); if (keyPair != null) { _logger.LogDebug("Using client-side certificate"); sslClientCertificate = new KeyCertificatePair(keyPair.PublicKey, keyPair.PrivateKey); } else { throw new ArgumentException( $"Could not usable find client certificate {clientCertificate} in certificate store."); } } var result = new SslCredentials(rootCertificatesAsPem, sslClientCertificate); return(result); }
private static KeyPair TryGetServerCertificateKeyPair( [NotNull] string certificate, [CanBeNull] string privateKeyFilePath) { KeyPair result; if (File.Exists(certificate)) { _logger.LogDebug("Using existing PEM file certificate: {cert}.", certificate); if (string.IsNullOrEmpty(privateKeyFilePath)) { throw new ArgumentException("Private key PEM file was not provided."); } if (!File.Exists(privateKeyFilePath)) { throw new ArgumentException( $"Private key PEM file {privateKeyFilePath} was not found."); } result = new KeyPair(File.ReadAllText(privateKeyFilePath), File.ReadAllText(certificate)); _logger.LogInformation("Using certificate from file {cert}", certificate); } else { _logger.LogDebug( "No certificate PEM file found using {cert}. Getting certificate from store.", certificate); if (!string.IsNullOrEmpty(privateKeyFilePath)) { result = GetMixedKeyPair(certificate, privateKeyFilePath); } else { // Find server certificate including private key from Store (Local Computer, Personal folder) result = CertificateUtils.FindKeyCertificatePairFromStore( certificate, new[] { X509FindType.FindBySubjectDistinguishedName, X509FindType.FindByThumbprint }, StoreName.My, StoreLocation.LocalMachine); } if (result == null) { _logger.LogInformation( "No certificate could be found by '{cert}'. Using insecure credentials (no TLS).", certificate); } else { _logger.LogInformation("Using certificate from certificate store for TLS."); } } return(result); }