Как распространить сертификат SSL на определенный IP-адрес? С#C#

Место общения программистов C#
Ответить
Anonymous
 Как распространить сертификат SSL на определенный IP-адрес? С#

Сообщение Anonymous »

Я создал программу на C#, которая обращается к SSL и пытается распространить его на некоторые IP-адреса.
Она работает правильно и возвращает успех, но когда я открываю IP-адрес с помощью SSL, она не работает, только с http. .
Program.cs:

Код: Выделить всё

using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Text.Json;
using UnionFunctionality;
using Union_conf;

namespace Union_new
{
public class Program
{
static void Main(string[] args)
{
// Carregar as configurações do arquivo JSON
string configFilePath = "C:\\union\\union\\union\\Config.json";
Config config = LoadConfigFromJson(configFilePath);

if (config != null)
{
// Obter os endereços IP e portas do banco de dados
List addressPortList = GetAddressPortListFromDatabase();

// Certificado SSL
string certificatePath = config.CaminhoCertificado;
string certificatePassword = "";

foreach (var addressPort in addressPortList)
{
string address = addressPort.Item1;
int port = addressPort.Item2;

// Configurar e iniciar o servidor HTTPS
ConfigureAndStartHttpsServer(address, port, certificatePath, certificatePassword);
}
}

Console.ReadKey();
}

static List GetAddressPortListFromDatabase()
{
// Simulação de obtenção de endereços IP e portas do banco de dados
var addressPortList = new List
{
Tuple.Create("teste.nomedaempresa.com", 443),
// Adicione mais endereços e portas conforme necessário
};
return addressPortList;
}

static void ConfigureAndStartHttpsServer(string address, int port, string certificatePath, string certificatePassword)
{
var server = new HttpServer(new HttpServerOptions
{
Port = port,
UseHttps = true,
Certificate = new X509Certificate2(certificatePath, certificatePassword)
});
server.Start();
}

static Config LoadConfigFromJson(string filePath)
{
try
{
// Verificar se o arquivo JSON existe
if (File.Exists(filePath))
{
// Ler o conteúdo do arquivo JSON
string json = File.ReadAllText(filePath);

// Deserializar o JSON para uma instância de Config
return JsonSerializer.Deserialize(json);
}
else
{
throw new FileNotFoundException($"O arquivo JSON de configuração não foi encontrado em: {filePath}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Erro ao carregar o arquivo de configuração: {ex.Message}");
return null;
}
}
}
}
Functionality.cs:

Код: Выделить всё

using System;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;

namespace UnionFunctionality
{
public class HttpServerOptions
{
public int Port { get; set; }
public bool UseHttps { get; set; }
public X509Certificate2 Certificate { get; set; }
}

public class HttpServer
{
private readonly HttpListener _listener;

public event EventHandler RequestReceived;

public HttpServer(HttpServerOptions options)
{
_listener = new HttpListener();
string prefix = options.UseHttps ? $"https://+:{options.Port}/" : $"http://+:{options.Port}/";
_listener.Prefixes.Add(prefix);

if (options.UseHttps &&  options.Certificate != null)
{
ConfigureSsl(options.Certificate, options.Port);
}
}

private void ConfigureSsl(X509Certificate2 certificate, int port)
{
// Configure o certificado SSL para o HttpListener
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

// Adicione a configuração SSL usando netsh
string certhash = certificate.GetCertHashString();
string appid = Guid.NewGuid().ToString();

var startInfo = new System.Diagnostics.ProcessStartInfo("netsh", $"http add sslcert ipport=0.0.0.0:{port} certhash={certhash} appid={{appid}}")
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};

var process = new System.Diagnostics.Process { StartInfo = startInfo };
process.Start();
process.WaitForExit();
}

public void Start()
{
try
{
_listener.Start();
Console.WriteLine("Servidor HTTPS iniciado.");

Task.Run(async () =>
{
while (_listener.IsListening)
{
var context = await _listener.GetContextAsync();
OnRequestReceived(context);
_ = Task.Run(() => HandleContextAsync(context));
}
});
}
catch (Exception ex)
{
Console.WriteLine($"Erro ao iniciar o servidor HTTPS: {ex}");
}
}

private async Task HandleContextAsync(HttpListenerContext context)
{
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;

try
{
response.ContentType = "text/plain";
response.StatusCode = 200;

string responseString = "Hello, HTTPS!";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;

using (var outputStream = response.OutputStream)
{
await outputStream.WriteAsync(buffer, 0, buffer.Length);
}
}
catch (Exception ex)
{
Console.WriteLine($"Erro ao lidar com a solicitação HTTPS: {ex}");
response.StatusCode = 500;
}
finally
{
response.Close();
}
}

protected virtual void OnRequestReceived(HttpListenerContext context)
{
RequestReceived?.Invoke(this, context);
}
}
}
Config.json:

Код: Выделить всё

{
"SenhaChavePrivada": "",
"CaminhoCertificado": "C:\\conf\\certificado.pem",
"SenhaCertificado": "",
"CaminhoChavePrivada": "C:\\conf\\certificado.pem"
}
Config.cs:

Код: Выделить всё

using System;
using System.IO;
using System.Text.Json;

namespace Union_conf
{
public class Config
{
public string RemoteHost { get; set; }
public string SenhaChavePrivada { get; set; }
public string CaminhoChavePrivada { get; set; }
public string CaminhoCertificado { get; set; }

public static Config LoadFromJson(string filePath)
{
try
{
string jsonString = File.ReadAllText(filePath);
return JsonSerializer.Deserialize(jsonString);
}
catch (Exception ex)
{
Console.WriteLine($"Erro ao carregar o arquivo de configuração: {ex.Message}");
return null;
}
}
}
}
Когда я поместил сертификат, указывающий непосредственно на tomcat (server.xml), он работал, когда я поместил его на IP-адрес tomcat, он не работал.
Я бы хотел узнать, есть ли способ сделать это, указав непосредственно на IP.

Подробнее здесь: https://stackoverflow.com/questions/785 ... ip-c-sharp
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»