-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDefaultDecryptionService.cs
49 lines (40 loc) · 1.67 KB
/
DefaultDecryptionService.cs
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
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Amazon.KeyManagementService;
using Amazon.KeyManagementService.Model;
using Lambdajection.Framework;
namespace Lambdajection.Encryption
{
/// <summary>
/// Default decryption service - uses KMS to decrypt values.
/// </summary>
public class DefaultDecryptionService : IDecryptionService
{
private readonly IAmazonKeyManagementService kmsClient;
/// <summary>
/// Initializes a new instance of the <see cref="DefaultDecryptionService" /> class.
/// </summary>
/// <param name="kmsClient">The KMS Client to use when decrypting values.</param>
public DefaultDecryptionService(IAmazonKeyManagementService kmsClient)
{
this.kmsClient = kmsClient;
}
/// <inheritdoc />
[RequiresIamPermission("kms:Decrypt")]
public virtual async Task<string> Decrypt(string ciphertext, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
using var stream = new MemoryStream();
var byteArray = Convert.FromBase64String(ciphertext);
await stream.WriteAsync(byteArray, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
var request = new DecryptRequest { CiphertextBlob = stream };
var response = await kmsClient.DecryptAsync(request, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
using var reader = new StreamReader(response.Plaintext);
return await reader.ReadToEndAsync();
}
}
}