using System.Security.Cryptography; using System.Text.Json; using Jose; namespace Duplicati.Library.RemoteControl; /// /// Helper class for transport related functions /// internal static class TransportHelper { /// /// Creates a signed message in JWT format using the provided private key /// /// The message to sign /// The private key to sign with /// The signed message public static string CreateSignedMessage(EnvelopedMessage message, RSA privateKey) { return JWT.Encode( JsonSerializer.Serialize(message, options: KeepRemoteConnection.JsonOptions), new Jwk(privateKey, false), JwsAlgorithm.RS256, extraHeaders: new Dictionary() { { "encrypted", "false" }, { "version", "1" } } ); } /// /// Creates an encrypted message in JWE format using the provided public key /// /// The message to encrypt /// The public key to encrypt with /// The encrypted message public static string CreateEncryptedMessage(EnvelopedMessage message, RSA publicKey) { return JWT.Encode( JsonSerializer.Serialize(message, options: KeepRemoteConnection.JsonOptions), new Jwk(publicKey, false), JweAlgorithm.RSA_OAEP_256, JweEncryption.A256CBC_HS512, extraHeaders: new Dictionary() { { "encrypted", "true" }, { "version", "1" } } ); } /// /// Parses a signed message using the provided public key /// /// The signed message to parse /// The public key to verify with /// The parsed message public static EnvelopedMessage ParseFromSignedMessage(string message, RSA publicKey) => ParsedFromEncodedMessage(message, publicKey, false); /// /// Parses an encrypted message using the provided key /// /// The encrypted message to parse /// The private key to decrypt with /// The parsed message public static EnvelopedMessage ParseFromEncryptedMessage(string message, RSA privateKey) => ParsedFromEncodedMessage(message, privateKey, true); /// /// Parses an encrypted message using the provided key /// /// The encrypted message to parse /// The private key to decrypt with /// The parsed message private static EnvelopedMessage ParsedFromEncodedMessage(string message, RSA key, bool isPrivateKey) { try { return EnvelopedMessage.ForceParse(JWT.Decode(message, new Jwk(key, isPrivateKey))); } catch (Exception ex) { throw new InvalidOperationException("Invalid message", ex); } } }