This repository was archived by the owner on Oct 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEncryptionHandler.cs
More file actions
60 lines (49 loc) · 2.35 KB
/
EncryptionHandler.cs
File metadata and controls
60 lines (49 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using Microsoft.Extensions.Options;
using OpenKMS.Abstractions;
using OpenKMS.Models;
namespace OpenKMS;
/// <summary>
/// An opinionated abstraction for implementing <see cref="IEncryptionHandler"/>.
/// </summary>
/// <typeparam name="TOptions">The type for the options used to configure the encryption handler.</typeparam>
public abstract class EncryptionHandler<TOptions> : IEncryptionHandler where TOptions : EncryptionHandlerOptions, new()
{
/// <summary>
/// Gets or sets the <see cref="EncryptionScheme"/> associated with this encryption handler.
/// </summary>
public EncryptionScheme Scheme { get; private set; } = default!;
/// <summary>
/// Gets or sets the options associated with this encryption handler.
/// </summary>
public TOptions Options { get; private set; } = default!;
public abstract Task<EncryptResult> EncryptAsync(byte[] plaintext, byte[]? additionalAuthenticatedData = null,
CancellationToken cancellationToken = default);
public abstract Task<byte[]> DecryptAsync(JsonWebKey key, byte[] ciphertext, byte[]? iv = null,
byte[]? authenticationTag = null, byte[]? additionalAuthenticatedData = null,
CancellationToken cancellationToken = default);
public abstract bool CanDecrypt(JsonWebKey key);
/// <summary>
/// Gets the <see cref="IOptionsMonitor{TOptions}"/> to detect changes to options.
/// </summary>
protected IOptionsMonitor<TOptions> OptionsMonitor { get; }
/// <summary>
/// Initializes a new instance of <see cref="EncryptionHandler{TOptions}"/>.
/// </summary>
/// <param name="options">The monitor for the options instance.</param>
protected EncryptionHandler(IOptionsMonitor<TOptions> options) => OptionsMonitor = options;
/// <summary>
/// Initialize the handler, resolve the options and validate them.
/// </summary>
/// <returns></returns>
public async Task InitializeAsync(EncryptionScheme scheme)
{
Scheme = scheme ?? throw new ArgumentNullException(nameof(scheme));
Options = OptionsMonitor.Get(Scheme.Name);
await InitializeHandlerAsync();
}
/// <summary>
/// Called after options/events have been initialized for the handler to finish initializing itself.
/// </summary>
/// <returns>A task</returns>
protected virtual Task InitializeHandlerAsync() => Task.CompletedTask;
}