< Summary

Information
Class: AsiBackbone.Signing.ManagedKey.GovernanceVerificationKey
Assembly: AsiBackbone.Signing.ManagedKey
File(s): /home/runner/work/AsiBackbone/AsiBackbone/src/AsiBackbone.Signing.ManagedKey/GovernanceVerificationKey.cs
Line coverage
77%
Covered lines: 72
Uncovered lines: 21
Coverable lines: 93
Total lines: 184
Line coverage: 77.4%
Branch coverage
50%
Covered branches: 18
Total branches: 36
Branch coverage: 50%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
FromPem(...)100%4480%
FromJwk(...)36.36%662255%
FromRsaPem(...)100%11100%
FromEcdsaPem(...)50%22100%
EnsureRsaSize(...)100%22100%
ValidateIdentity(...)100%11100%
RequiredString(...)50%66100%
DecodeBase64Url(...)100%11100%

File(s)

/home/runner/work/AsiBackbone/AsiBackbone/src/AsiBackbone.Signing.ManagedKey/GovernanceVerificationKey.cs

#LineLine coverage
 1using System.Security.Cryptography;
 2using System.Text.Json;
 3
 4namespace AsiBackbone.Signing.ManagedKey;
 5
 6/// <summary>Represents one trusted public verification-key version.</summary>
 7public sealed class GovernanceVerificationKey
 8{
 69    private GovernanceVerificationKey(
 610        string keyId,
 611        string keyVersion,
 612        string signatureAlgorithm,
 613        byte[] subjectPublicKeyInfo,
 614        bool isRevoked)
 15    {
 616        KeyId = keyId;
 617        KeyVersion = keyVersion;
 618        SignatureAlgorithm = signatureAlgorithm;
 619        SubjectPublicKeyInfo = subjectPublicKeyInfo;
 620        IsRevoked = isRevoked;
 621    }
 22
 23    /// <summary>Gets the stable key identifier.</summary>
 24    public string KeyId { get; }
 25
 26    /// <summary>Gets the stable key version.</summary>
 27    public string KeyVersion { get; }
 28
 29    /// <summary>Gets the required signature algorithm descriptor.</summary>
 30    public string SignatureAlgorithm { get; }
 31
 32    /// <summary>Gets a value indicating whether this version is revoked.</summary>
 33    public bool IsRevoked { get; }
 34
 35    internal byte[] SubjectPublicKeyInfo { get; }
 36
 37    /// <summary>Creates a trusted key from an SPKI public-key PEM.</summary>
 38    public static GovernanceVerificationKey FromPem(
 39        string keyId,
 40        string keyVersion,
 41        string signatureAlgorithm,
 42        string publicKeyPem,
 43        bool isRevoked = false,
 44        int minimumRsaKeySize = 2048)
 45    {
 746        ValidateIdentity(keyId, keyVersion, signatureAlgorithm);
 747        ArgumentException.ThrowIfNullOrWhiteSpace(publicKeyPem);
 48
 749        if (publicKeyPem.Contains("PRIVATE KEY", StringComparison.Ordinal))
 50        {
 151            throw new ArgumentException("Trusted verification material must not contain a private key.", nameof(publicKe
 52        }
 53
 54        try
 55        {
 656            return signatureAlgorithm switch
 657            {
 558                ManagedKeySignatureAlgorithms.RsaPssSha256 => FromRsaPem(
 559                    keyId.Trim(), keyVersion.Trim(), signatureAlgorithm, publicKeyPem, isRevoked, minimumRsaKeySize),
 160                ManagedKeySignatureAlgorithms.EcdsaP256Sha256 => FromEcdsaPem(
 161                    keyId.Trim(), keyVersion.Trim(), signatureAlgorithm, publicKeyPem, isRevoked),
 062                _ => throw new ArgumentException("The verification-key signature algorithm is unsupported.", nameof(sign
 663            };
 64        }
 065        catch (CryptographicException exception)
 66        {
 067            throw new ArgumentException("The verification key is not valid public-key material.", nameof(publicKeyPem), 
 68        }
 569    }
 70
 71    /// <summary>Creates a trusted key from an RSA or EC public JWK.</summary>
 72    public static GovernanceVerificationKey FromJwk(
 73        string keyId,
 74        string keyVersion,
 75        string signatureAlgorithm,
 76        string publicJwk,
 77        bool isRevoked = false,
 78        int minimumRsaKeySize = 2048)
 79    {
 180        ValidateIdentity(keyId, keyVersion, signatureAlgorithm);
 181        ArgumentException.ThrowIfNullOrWhiteSpace(publicJwk);
 82
 183        using var document = JsonDocument.Parse(publicJwk);
 184        JsonElement root = document.RootElement;
 185        if (root.TryGetProperty("d", out _)
 186            || root.TryGetProperty("p", out _)
 187            || root.TryGetProperty("q", out _)
 188            || root.TryGetProperty("dp", out _)
 189            || root.TryGetProperty("dq", out _)
 190            || root.TryGetProperty("qi", out _))
 91        {
 092            throw new ArgumentException("Trusted verification material must not contain a private key.", nameof(publicJw
 93        }
 94
 195        string kty = RequiredString(root, "kty", nameof(publicJwk));
 96        try
 97        {
 198            if (string.Equals(kty, "RSA", StringComparison.Ordinal)
 199                && signatureAlgorithm == ManagedKeySignatureAlgorithms.RsaPssSha256)
 100            {
 1101                using var rsa = RSA.Create();
 1102                rsa.ImportParameters(new RSAParameters
 1103                {
 1104                    Modulus = DecodeBase64Url(RequiredString(root, "n", nameof(publicJwk))),
 1105                    Exponent = DecodeBase64Url(RequiredString(root, "e", nameof(publicJwk)))
 1106                });
 1107                EnsureRsaSize(rsa, minimumRsaKeySize);
 1108                return new(keyId.Trim(), keyVersion.Trim(), signatureAlgorithm, rsa.ExportSubjectPublicKeyInfo(), isRevo
 109            }
 110
 0111            if (string.Equals(kty, "EC", StringComparison.Ordinal)
 0112                && signatureAlgorithm == ManagedKeySignatureAlgorithms.EcdsaP256Sha256
 0113                && string.Equals(RequiredString(root, "crv", nameof(publicJwk)), "P-256", StringComparison.Ordinal))
 114            {
 0115                using var ecdsa = ECDsa.Create(new ECParameters
 0116                {
 0117                    Curve = ECCurve.NamedCurves.nistP256,
 0118                    Q = new ECPoint
 0119                    {
 0120                        X = DecodeBase64Url(RequiredString(root, "x", nameof(publicJwk))),
 0121                        Y = DecodeBase64Url(RequiredString(root, "y", nameof(publicJwk)))
 0122                    }
 0123                });
 0124                return new(keyId.Trim(), keyVersion.Trim(), signatureAlgorithm, ecdsa.ExportSubjectPublicKeyInfo(), isRe
 125            }
 0126        }
 0127        catch (CryptographicException exception)
 128        {
 0129            throw new ArgumentException("The JWK is not valid public-key material.", nameof(publicJwk), exception);
 130        }
 131
 0132        throw new ArgumentException("The JWK key type, curve, or signature algorithm is unsupported.", nameof(publicJwk)
 1133    }
 134
 135    private static GovernanceVerificationKey FromRsaPem(
 136        string keyId, string keyVersion, string algorithm, string pem, bool revoked, int minimumRsaKeySize)
 137    {
 5138        using var rsa = RSA.Create();
 5139        rsa.ImportFromPem(pem);
 5140        EnsureRsaSize(rsa, minimumRsaKeySize);
 4141        return new(keyId, keyVersion, algorithm, rsa.ExportSubjectPublicKeyInfo(), revoked);
 4142    }
 143
 144    private static GovernanceVerificationKey FromEcdsaPem(
 145        string keyId, string keyVersion, string algorithm, string pem, bool revoked)
 146    {
 1147        using var ecdsa = ECDsa.Create();
 1148        ecdsa.ImportFromPem(pem);
 1149        return ecdsa.KeySize != 256
 1150            ? throw new ArgumentException("ECDSA verification keys must use the P-256 curve.", nameof(pem))
 1151            : new(keyId, keyVersion, algorithm, ecdsa.ExportSubjectPublicKeyInfo(), revoked);
 1152    }
 153
 154    private static void EnsureRsaSize(RSA rsa, int minimumRsaKeySize)
 155    {
 6156        ArgumentOutOfRangeException.ThrowIfLessThan(minimumRsaKeySize, 2048);
 6157        if (rsa.KeySize < minimumRsaKeySize)
 158        {
 1159            throw new ArgumentException($"RSA verification keys must be at least {minimumRsaKeySize} bits.");
 160        }
 5161    }
 162
 163    private static void ValidateIdentity(string keyId, string keyVersion, string signatureAlgorithm)
 164    {
 8165        ArgumentException.ThrowIfNullOrWhiteSpace(keyId);
 8166        ArgumentException.ThrowIfNullOrWhiteSpace(keyVersion);
 8167        ArgumentException.ThrowIfNullOrWhiteSpace(signatureAlgorithm);
 8168    }
 169
 170    private static string RequiredString(JsonElement root, string name, string parameterName)
 171    {
 3172        return !root.TryGetProperty(name, out JsonElement value) || value.ValueKind != JsonValueKind.String
 3173            || string.IsNullOrWhiteSpace(value.GetString())
 3174            ? throw new ArgumentException($"The JWK requires a non-empty '{name}' member.", parameterName)
 3175            : value.GetString()!;
 176    }
 177
 178    private static byte[] DecodeBase64Url(string value)
 179    {
 2180        string padded = value.Replace('-', '+').Replace('_', '/');
 2181        padded = padded.PadRight(padded.Length + ((4 - (padded.Length % 4)) % 4), '=');
 2182        return Convert.FromBase64String(padded);
 183    }
 184}