< Summary

Information
Class: Elsa.Secrets.Services.DefaultSecretValueProtector
Assembly: Elsa.Secrets
File(s): /home/runner/work/elsa-core/elsa-core/src/modules/Elsa.Secrets/Services/DefaultSecretValueProtector.cs
Line coverage
100%
Covered lines: 26
Uncovered lines: 0
Coverable lines: 26
Total lines: 52
Line coverage: 100%
Branch coverage
100%
Covered branches: 16
Total branches: 16
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
Protect(...)100%11100%
Unprotect(...)100%44100%
GetKey()100%1212100%

File(s)

/home/runner/work/elsa-core/elsa-core/src/modules/Elsa.Secrets/Services/DefaultSecretValueProtector.cs

#LineLine coverage
 1using System.Security.Cryptography;
 2using Microsoft.Extensions.Options;
 3
 4namespace Elsa.Secrets.Services;
 5
 696public class DefaultSecretValueProtector(IOptions<SecretsOptions> options) : ISecretValueProtector
 7{
 8    private const int NonceSize = 12;
 9    private const int TagSize = 16;
 10
 11    public string Protect(string value)
 12    {
 5113        var nonce = RandomNumberGenerator.GetBytes(NonceSize);
 5114        var plaintext = System.Text.Encoding.UTF8.GetBytes(value);
 5115        var ciphertext = new byte[plaintext.Length];
 5116        var tag = new byte[TagSize];
 17
 5118        using var aes = new AesGcm(GetKey(), TagSize);
 4719        aes.Encrypt(nonce, plaintext, ciphertext, tag);
 20
 4721        return string.Join(".", "v1", Convert.ToBase64String(nonce), Convert.ToBase64String(tag), Convert.ToBase64String
 4722    }
 23
 24    public string Unprotect(string protectedValue)
 25    {
 1626        var parts = protectedValue.Split('.');
 1627        if (parts.Length != 4 || parts[0] != "v1")
 328            throw new InvalidOperationException("The protected secret payload is not supported.");
 29
 1330        var nonce = Convert.FromBase64String(parts[1]);
 1231        var tag = Convert.FromBase64String(parts[2]);
 1232        var ciphertext = Convert.FromBase64String(parts[3]);
 1233        var plaintext = new byte[ciphertext.Length];
 34
 1235        using var aes = new AesGcm(GetKey(), TagSize);
 1236        aes.Decrypt(nonce, ciphertext, tag, plaintext);
 37
 1238        return System.Text.Encoding.UTF8.GetString(plaintext);
 1239    }
 40
 41    private byte[] GetKey()
 42    {
 6343        var key = options.Value.EncryptionKey;
 6344        if (key == null || key.Length == 0)
 245            throw new InvalidOperationException("Elsa Secrets encryption key is not configured. Configure SecretsOptions
 46
 6147        if (key.Length is not (16 or 24 or 32))
 248            throw new InvalidOperationException("Elsa Secrets encryption key must be exactly 16, 24, or 32 bytes.");
 49
 5950        return key;
 51    }
 52}