| | | 1 | | using System.Security.Cryptography; |
| | | 2 | | using System.Text; |
| | | 3 | | using System.Text.Json; |
| | | 4 | | using System.Text.Json.Serialization; |
| | | 5 | | using Elsa.Expressions.Contracts; |
| | | 6 | | using Elsa.Workflows.Serialization.Converters; |
| | | 7 | | |
| | | 8 | | namespace Elsa.Workflows; |
| | | 9 | | |
| | | 10 | | /// <inheritdoc /> |
| | | 11 | | public class Hasher : IHasher |
| | | 12 | | { |
| | | 13 | | private readonly JsonSerializerOptions _serializerOptions; |
| | | 14 | | |
| | 114 | 15 | | public Hasher(IWellKnownTypeRegistry wellKnownTypeRegistry) |
| | | 16 | | { |
| | 114 | 17 | | _serializerOptions = new JsonSerializerOptions |
| | 114 | 18 | | { |
| | 114 | 19 | | IncludeFields = true, |
| | 114 | 20 | | PropertyNameCaseInsensitive = true, |
| | 114 | 21 | | DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull |
| | 114 | 22 | | }; |
| | | 23 | | |
| | 114 | 24 | | _serializerOptions.Converters.Add(new TypeJsonConverter(wellKnownTypeRegistry)); |
| | 114 | 25 | | _serializerOptions.Converters.Add(new ExcludeFromHashConverterFactory()); |
| | 114 | 26 | | } |
| | | 27 | | |
| | | 28 | | /// <inheritdoc /> |
| | | 29 | | public string Hash(string value) |
| | | 30 | | { |
| | 4312 | 31 | | var data = SHA256.HashData(Encoding.UTF8.GetBytes(value)); |
| | 4312 | 32 | | return Convert.ToHexString(data); |
| | | 33 | | } |
| | | 34 | | |
| | | 35 | | /// <inheritdoc /> |
| | | 36 | | public string Hash(params object?[] values) |
| | | 37 | | { |
| | 9357 | 38 | | var strings = values.Select(Serialize).Where(x => !string.IsNullOrWhiteSpace(x)).ToList(); |
| | 4312 | 39 | | var input = string.Join("|", strings); |
| | 4312 | 40 | | return Hash(input); |
| | | 41 | | } |
| | | 42 | | |
| | | 43 | | private string Serialize(object? payload) |
| | | 44 | | { |
| | 5045 | 45 | | if(payload == null) |
| | 362 | 46 | | return string.Empty; |
| | | 47 | | |
| | 4683 | 48 | | if(payload is string s) |
| | 369 | 49 | | return s; |
| | | 50 | | |
| | 4314 | 51 | | return JsonSerializer.Serialize(payload, payload.GetType(), _serializerOptions); |
| | | 52 | | } |
| | | 53 | | } |