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); }