Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Makes AesGcm Sample Thread Safe #52

Merged
merged 7 commits into from
Feb 12, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 15 additions & 16 deletions src/Encryption/Codec/EncryptionCodec.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace TemporalioSamples.Encryption.Codec;
using Temporalio.Api.Common.V1;
using Temporalio.Converters;

public sealed class EncryptionCodec : IPayloadCodec, IDisposable
public sealed class EncryptionCodec : IPayloadCodec
{
public const string DefaultKeyID = "test-key-id";
public static readonly byte[] DefaultKey = System.Text.Encoding.ASCII.GetBytes("test-key-test-key-test-key-test!");
Expand All @@ -14,26 +14,18 @@ public sealed class EncryptionCodec : IPayloadCodec, IDisposable
private const int TagSize = 16;
private static readonly ByteString EncodingByteString = ByteString.CopyFromUtf8("binary/encrypted");

private readonly byte[] key;
private readonly ByteString keyIDByteString;
private readonly AesGcm aes;

public EncryptionCodec(string keyID = DefaultKeyID, byte[]? key = null)
{
KeyID = keyID;
keyIDByteString = ByteString.CopyFromUtf8(keyID);
aes = new(key ?? DefaultKey);
this.key = key ?? DefaultKey;
}

~EncryptionCodec() => Dispose();

public string KeyID { get; private init; }

public void Dispose()
{
aes.Dispose();
GC.SuppressFinalize(this);
}

public Task<IReadOnlyCollection<Payload>> EncodeAsync(IReadOnlyCollection<Payload> payloads) =>
Task.FromResult<IReadOnlyCollection<Payload>>(payloads.Select(p =>
{
Expand Down Expand Up @@ -79,15 +71,22 @@ private byte[] Encrypt(byte[] data)
RandomNumberGenerator.Fill(nonceSpan);

// Perform encryption
aes.Encrypt(nonceSpan, data, bytes.AsSpan(NonceSize + TagSize), bytes.AsSpan(NonceSize, TagSize));
return bytes;
using (var aes = new AesGcm(key))
{
aes.Encrypt(nonceSpan, data, bytes.AsSpan(NonceSize + TagSize), bytes.AsSpan(NonceSize, TagSize));
return bytes;
}
}

private byte[] Decrypt(byte[] data)
{
var bytes = new byte[data.Length - NonceSize - TagSize];
aes.Decrypt(
data.AsSpan(0, NonceSize), data.AsSpan(NonceSize + TagSize), data.AsSpan(NonceSize, TagSize), bytes.AsSpan());
return bytes;

using (var aes = new AesGcm(key))
{
aes.Decrypt(
data.AsSpan(0, NonceSize), data.AsSpan(NonceSize + TagSize), data.AsSpan(NonceSize, TagSize), bytes.AsSpan());
return bytes;
}
}
}
Loading