| | | 1 | | using System.Security.Cryptography; |
| | | 2 | | using System.Text; |
| | | 3 | | using Elsa.ExternalAuthentication.Contracts; |
| | | 4 | | using Elsa.ExternalAuthentication.Options; |
| | | 5 | | using Microsoft.Extensions.Options; |
| | | 6 | | |
| | | 7 | | namespace Elsa.ExternalAuthentication.Services; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// HMAC-SHA-256 handle hasher. It uses a configured shared key when present and a process-local |
| | | 11 | | /// key for single-node development otherwise. |
| | | 12 | | /// </summary> |
| | | 13 | | public sealed class HmacExternalAuthenticationHandleHasher : IExternalAuthenticationHandleHasher, IDisposable |
| | | 14 | | { |
| | | 15 | | private readonly byte[] _key; |
| | | 16 | | |
| | | 17 | | /// <summary> |
| | | 18 | | /// Creates a process-local hasher for tests and single-node development. |
| | | 19 | | /// </summary> |
| | 56 | 20 | | public HmacExternalAuthenticationHandleHasher() : this(RandomNumberGenerator.GetBytes(32)) |
| | | 21 | | { |
| | 56 | 22 | | } |
| | | 23 | | |
| | | 24 | | /// <summary> |
| | | 25 | | /// Creates a hasher from deployment-owned External Authentication options. |
| | | 26 | | /// </summary> |
| | | 27 | | public HmacExternalAuthenticationHandleHasher(IOptions<ExternalAuthenticationOptions> options) |
| | 15 | 28 | | : this(GetKey(options.Value.HandleHashing)) |
| | | 29 | | { |
| | 15 | 30 | | } |
| | | 31 | | |
| | 71 | 32 | | private HmacExternalAuthenticationHandleHasher(byte[] key) |
| | | 33 | | { |
| | 71 | 34 | | _key = key; |
| | 71 | 35 | | } |
| | | 36 | | |
| | 176 | 37 | | public string Hash(string value) => Convert.ToHexString(HMACSHA256.HashData(_key, Encoding.UTF8.GetBytes(value))); |
| | | 38 | | |
| | 36 | 39 | | public void Dispose() => CryptographicOperations.ZeroMemory(_key); |
| | | 40 | | |
| | | 41 | | private static byte[] GetKey(ExternalAuthenticationHandleHashingOptions? options) |
| | | 42 | | { |
| | 15 | 43 | | if (options is null) |
| | 0 | 44 | | throw new InvalidOperationException("External Authentication handle-hashing settings are required."); |
| | | 45 | | |
| | 15 | 46 | | if (string.IsNullOrWhiteSpace(options.SharedKeyBase64)) |
| | 13 | 47 | | return RandomNumberGenerator.GetBytes(32); |
| | | 48 | | |
| | | 49 | | try |
| | | 50 | | { |
| | 2 | 51 | | var key = Convert.FromBase64String(options.SharedKeyBase64); |
| | 2 | 52 | | if (key.Length >= 32) |
| | 2 | 53 | | return key; |
| | | 54 | | |
| | 0 | 55 | | CryptographicOperations.ZeroMemory(key); |
| | 0 | 56 | | } |
| | 0 | 57 | | catch (FormatException) |
| | | 58 | | { |
| | | 59 | | // The options validator reports the actionable configuration error at startup. |
| | 0 | 60 | | } |
| | | 61 | | |
| | 0 | 62 | | throw new InvalidOperationException("The External Authentication shared handle-hashing key must be valid base64 |
| | 2 | 63 | | } |
| | | 64 | | } |