Skip to content

Commit

Permalink
refactor: add ExtractSymmetricKey method
Browse files Browse the repository at this point in the history
  • Loading branch information
HunorTotBagi committed Feb 9, 2024
1 parent 8849591 commit 90d0fef
Showing 1 changed file with 23 additions and 2 deletions.
25 changes: 23 additions & 2 deletions Modules/Messages/src/Messages.Domain/Entities/Message.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
using System.Text;
using System.Text.Json;
using Backbone.Crypto;
using Backbone.Crypto.Implementations;
using Backbone.DevelopmentKit.Identity.ValueObjects;
using Backbone.Modules.Messages.Domain.Ids;
using Backbone.Tooling;
using Backbone.Tooling.JsonConverters;

namespace Backbone.Modules.Messages.Domain.Entities;

Expand Down Expand Up @@ -47,11 +49,30 @@ public void LoadBody(byte[] bytes)
Body = bytes;
}

public string Decrypt(string secretKey)
public string Decrypt(string serializedSecret)
{
var secretKey = ExtractSymmetricKey(serializedSecret);

return new LibsodiumSymmetricEncrypter().Decrypt(
ConvertibleString.FromByteArray(Body),
ConvertibleString.FromUtf8(secretKey))
ConvertibleString.FromByteArray(secretKey))
.Utf8Representation;
}

private static byte[] ExtractSymmetricKey(string serializedSecret)
{
var deserializedSecret = JsonSerializer.Deserialize<Secret>(serializedSecret,
new JsonSerializerOptions { Converters = { new UrlSafeBase64ToByteArrayJsonConverter() } });

var key = Convert.FromBase64String(deserializedSecret!.key + "=");
return key;
}

private class Secret
{
/**
* Algorithm (`alg`) field is omitted due to not being used in the code.
*/
public required string key { get; init; }
}
}

0 comments on commit 90d0fef

Please sign in to comment.