patbef-ServiceInside/ServiceInside/Service/ServiceOutside.cs

74 lines
2.6 KiB
C#
Raw Normal View History

2024-01-29 16:26:54 +01:00
using ServiceShared;
using ServiceShared.Crypto;
using ServiceShared.Models.Request;
using ServiceShared.Models.Response;
namespace ServiceInside.Service
{
public static class ServiceOutside
{
/// <summary>
/// URL of ServiceOutside
/// </summary>
private static string ServiceOutsideURL;
/// <summary>
/// Sets the URL of ServiceOutside
/// </summary>
/// <param name="serviceOutsideURL">Url of OutsideService</param>
public static void SetServiceOutsideURL(string serviceOutsideURL)
{
ServiceOutsideURL = serviceOutsideURL;
}
/// <summary>
/// Sends notification to the ServiceOutside
/// </summary>
/// <param name="notification">notification that should be sent to the outside service</param>
public static void Notify(Notification notification)
{
try
{
KeyPair keyPair = Curve25519.GenerateKeyPair();
EncryptedRequest encryptedRequest = new EncryptedRequest("Notification", notification, ServiceOutsideDeriveKey(keyPair));
ServiceShared.Https.Request.PostWithoutResponse(ServiceOutsideURL, "serviceinside", "notification", encryptedRequest, keyPair);
}
catch (Exception ex)
{
Log.Critical(ex, "ServiceInside.Service.ServiceOutside", "Notify");
}
}
/// <summary>
/// Shared derive key from outside service over (exchange controller)
/// </summary>
/// <param name="keyPair">KeyPair from the InsideService</param>
/// <returns></returns>
private static byte[] ServiceOutsideDeriveKey(KeyPair keyPair)
{
byte[] result = null;
try
{
PublicKey publicKey = ServiceShared.Https.Request.GetPublicKey(ServiceOutsideURL);
if(publicKey != null && !string.IsNullOrEmpty(publicKey.key))
{
byte[] base64Encoded = Convert.FromBase64String(publicKey.key);
result = keyPair.GetSharedKey(publicKey.key);
}
else
{
Log.Critical(new Exception("Could not get public key from the outside service"), "ServiceInside.Service.ServiceOutside", "ServiceOutsideDeriveKey");
}
}
catch (Exception ex)
{
Log.Critical(ex, "ServiceInside.Service.ServiceOutside", "ServiceOutsideDeriveKey(KeyPair)");
}
return result;
}
}
}