From caecebfcf157aae4c629ac15d32480183568ae75 Mon Sep 17 00:00:00 2001
From: Patrick Scheid
Date: Wed, 2 Dec 2026 21:59:09 +0100
Subject: [PATCH] Throw the documented exception for a null, a small RSA key
and a plugin's mistake
From the 2026-11-30 review (S5).
A null argument: ten Parse methods and every identity's TryUnwrap threw
NullReferenceException. They now throw ArgumentNullException, as the
others already did.
A small RSA key: SshRsaIdentity.Recipient threw ArgumentException for a
key under 2048 bits that Parse had accepted, and a passphrase-protected
one was refused when read, so a file made for it could not be opened. As
in go-age, an identity of any size now has a recipient and decrypts; the
size is checked where a key is read as a recipient, and again when
wrapping to it, which is an AgeException. The new test key
rsa_1024_aes256ctr was made for this (passphrase hunter2, as the others).
A plugin's file key of the wrong size was an AgeFormatException, a
malformed file; it is the plugin's mistake, an AgePluginException, and
is found where the fuzzer's plugin-client target can see it.
An AgePlugin handler that returns null, or a recipient that wraps to a
null stanza, was an exception out of Run. It is now that key's error to
the client and exit code 3.
---
Age.Tests/DocumentedExceptionsTests.cs | 229 ++++++++++++++++++
Age.Tests/SshTests.cs | 6 +-
.../TestData/EncryptedSsh/rsa_1024_aes256ctr | 17 ++
Age/Plugin/AgePlugin.cs | 7 +-
Age/Recipients/EncryptedIdentityFile.cs | 2 +
Age/Recipients/EncryptedSshIdentity.cs | 10 +-
Age/Recipients/FileKeyIdentity.cs | 2 +
Age/Recipients/IIdentity.cs | 2 +
Age/Recipients/MlKem768P256TagRecipient.cs | 2 +
Age/Recipients/MlKem768X25519Identity.cs | 3 +
Age/Recipients/MlKem768X25519Recipient.cs | 2 +
Age/Recipients/P256TagRecipient.cs | 2 +
Age/Recipients/Passphrase.cs | 1 +
Age/Recipients/PluginIdentity.cs | 14 +-
Age/Recipients/SshEd25519Identity.cs | 3 +
Age/Recipients/SshEd25519Recipient.cs | 2 +
Age/Recipients/SshIdentity.cs | 2 +
Age/Recipients/SshRsaIdentity.cs | 3 +
Age/Recipients/SshRsaRecipient.cs | 23 +-
Age/Recipients/X25519Identity.cs | 3 +
Age/Recipients/X25519Recipient.cs | 2 +
TODO.md | 2 +-
22 files changed, 325 insertions(+), 14 deletions(-)
create mode 100644 Age.Tests/DocumentedExceptionsTests.cs
create mode 100644 Age.Tests/TestData/EncryptedSsh/rsa_1024_aes256ctr
diff --git a/Age.Tests/DocumentedExceptionsTests.cs b/Age.Tests/DocumentedExceptionsTests.cs
new file mode 100644
index 0000000..9cd4e6a
--- /dev/null
+++ b/Age.Tests/DocumentedExceptionsTests.cs
@@ -0,0 +1,229 @@
+using System.Security.Cryptography;
+using AgeSharp;
+using AgeSharp.Crypto;
+using Xunit;
+
+namespace Age.Tests;
+
+///
+/// Failures that used to come out as an exception nobody documented, or as one that blamed the
+/// wrong party: a caller's null as a , a plugin's mistake as
+/// a malformed file, a small RSA key as a bad argument to a constructor the caller never called.
+///
+public class DocumentedExceptionsTests
+{
+ // --- a caller's null is an ArgumentNullException -------------------------------------------
+
+ public static TheoryData ParsersGivenNull => new()
+ {
+ { "Identities.Parse", () => Identities.Parse(null!) },
+ { "Identities.ParseOne", () => Identities.ParseOne(null!) },
+ { "Recipients.Parse", () => Recipients.Parse(null!) },
+ { "Recipients.ParseOne", () => Recipients.ParseOne(null!) },
+ { "X25519Identity.Parse", () => X25519Identity.Parse(null!) },
+ { "X25519Recipient.Parse", () => X25519Recipient.Parse(null!) },
+ { "MlKem768X25519Identity.Parse", () => MlKem768X25519Identity.Parse(null!) },
+ { "MlKem768X25519Recipient.Parse", () => MlKem768X25519Recipient.Parse(null!) },
+ { "P256TagRecipient.Parse", () => P256TagRecipient.Parse(null!) },
+ { "MlKem768P256TagRecipient.Parse", () => MlKem768P256TagRecipient.Parse(null!) },
+ { "PluginRecipient.Parse", () => PluginRecipient.Parse(null!) },
+ { "PluginIdentity.Parse", () => PluginIdentity.Parse(null!) },
+ { "SshIdentity.Parse(pem)", () => SshIdentity.Parse(null!) },
+ { "SshIdentity.Parse(pem, passphrase)", () => SshIdentity.Parse(null!, () => []) },
+ { "SshIdentity.Parse(pem, publicKey, passphrase)", () => SshIdentity.Parse(null!, "ssh-rsa AAAA", () => []) },
+ { "SshEd25519Identity.Parse", () => SshEd25519Identity.Parse(null!) },
+ { "SshRsaIdentity.Parse", () => SshRsaIdentity.Parse(null!) },
+ { "SshEd25519Recipient.Parse", () => SshEd25519Recipient.Parse(null!) },
+ { "SshRsaRecipient.Parse", () => SshRsaRecipient.Parse(null!) },
+ };
+
+ [Theory]
+ [MemberData(nameof(ParsersGivenNull))]
+ public void AParserGivenNull_ThrowsArgumentNullException(string which, Action parse)
+ {
+ Assert.True(which.Length > 0);
+ Assert.Throws(parse);
+ }
+
+ public static TheoryData> EveryIdentity => new()
+ {
+ { "X25519", X25519Identity.Generate },
+ { "ML-KEM-768-X25519", MlKem768X25519Identity.Generate },
+ { "passphrase", () => new Passphrase("pw") },
+ { "SSH Ed25519", () => SshEd25519Identity.Parse(SshKeys.Ed25519Pem()) },
+ { "SSH RSA", () => SshRsaIdentity.Parse(SshKeys.RsaPem()) },
+ { "plugin", () => PluginIdentity.Parse(Bech32.Encode("AGE-PLUGIN-FROOD-", [1]).ToUpperInvariant()) },
+ { "file key", () => new FileKeyIdentity(FileKey.From(new byte[FileKey.Size])) },
+ };
+
+ [Theory]
+ [MemberData(nameof(EveryIdentity))]
+ public void AnIdentityGivenANullStanza_ThrowsArgumentNullException(string which, Func make)
+ {
+ Assert.True(which.Length > 0);
+ using var identity = make();
+
+ Assert.Throws(() => identity.TryUnwrap((Stanza)null!, new byte[FileKey.Size]));
+ Assert.Throws(() => identity.TryUnwrap((IReadOnlyList)null!, new byte[FileKey.Size]));
+ }
+
+ // --- a small RSA key is refused where it would be used, as go-age refuses it ----------------
+
+ // go-age decrypts with an RSA key of any size, and so does AgeSharp; neither encrypts to one
+ // under 2048 bits. The identity still has a recipient, as the interface says it has: it is
+ // wrapping to it that is refused.
+ [Fact]
+ public void ASmallRsaIdentity_HasARecipient_WhichRefusesToWrap()
+ {
+ using var rsa = RSA.Create(1024);
+ using var identity = SshRsaIdentity.Parse(rsa.ExportRSAPrivateKeyPem());
+
+ var recipient = identity.Recipient;
+ Assert.Same(recipient, ((IIdentityWithRecipient)identity).Recipient);
+ Assert.StartsWith("ssh-rsa ", recipient.ToString(), StringComparison.Ordinal);
+
+ var ex = Assert.Throws(() => new Recipients(recipient).Encrypt("x"u8));
+ Assert.Equal("RSA key must be at least 2048 bits, got 1024", ex.Message);
+ }
+
+ // The same key read as a recipient is refused at once, as before.
+ [Fact]
+ public void ASmallRsaRecipientLine_IsStillRefusedWhenParsed()
+ {
+ using var rsa = RSA.Create(1024);
+ using var identity = SshRsaIdentity.Parse(rsa.ExportRSAPrivateKeyPem());
+
+ var ex = Assert.Throws(() => Recipients.ParseOne(identity.Recipient.ToString()));
+ Assert.Equal("RSA key must be at least 2048 bits, got 1024", ex.Message);
+ }
+
+ // A passphrase-protected key is no different: it used to be refused when it was read, so a
+ // file made for it long ago could not be opened at all.
+ [Fact]
+ public void ASmallProtectedRsaIdentity_Decrypts_AndRefusesToWrap()
+ {
+ var asked = 0;
+ var pem = File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "TestData", "EncryptedSsh", "rsa_1024_aes256ctr"));
+
+ using var identity = SshIdentity.Parse(pem, () =>
+ {
+ asked++;
+ return "hunter2".ToCharArray();
+ });
+
+ var recipient = ((IIdentityWithRecipient)identity).Recipient;
+ var refused = Assert.Throws(() => new Recipients(recipient).Encrypt("x"u8));
+ Assert.Equal("RSA key must be at least 2048 bits, got 1024", refused.Message);
+ Assert.Equal(0, asked);
+
+ // Neither AgeSharp nor go-age writes such a stanza any more, so the test makes one: the
+ // file key under RSA-OAEP with SHA-256 and age's label, tagged with the key's fingerprint.
+ byte[] fileKey = [.. Enumerable.Range(1, 16).Select(i => (byte)i)];
+ var wire = Convert.FromBase64String(recipient.ToString()!.Split(' ')[1]);
+ var oaep = new Org.BouncyCastle.Crypto.Encodings.OaepEncoding(
+ new Org.BouncyCastle.Crypto.Engines.RsaBlindedEngine(),
+ new Org.BouncyCastle.Crypto.Digests.Sha256Digest(), new Org.BouncyCastle.Crypto.Digests.Sha256Digest(),
+ "age-encryption.org/v1/ssh-rsa"u8.ToArray());
+ oaep.Init(true, Org.BouncyCastle.Crypto.Utilities.OpenSshPublicKeyUtilities.ParsePublicKey(wire));
+ var stanza = new Stanza("ssh-rsa", [Base64Unpadded.Encode(SHA256.HashData(wire).AsSpan(0, 4))], oaep.ProcessBlock(fileKey, 0, fileKey.Length));
+
+ var unwrapped = new byte[FileKey.Size];
+ Assert.True(identity.TryUnwrap(stanza, unwrapped));
+ Assert.Equal(fileKey, unwrapped);
+ Assert.Equal(1, asked);
+ }
+
+ // --- a plugin's mistake is the plugin's -----------------------------------------------------
+
+ [Theory]
+ [InlineData("QUFB", 3)]
+ [InlineData("", 0)]
+ [InlineData("AAAAAAAAAAAAAAAAAAAAAAA", 17)]
+ public void AFileKeyOfTheWrongSizeFromAPlugin_IsAPluginException(string body, int size)
+ {
+ var identity = PluginIdentity.Parse(Bech32.Encode("AGE-PLUGIN-FROOD-", [1]).ToUpperInvariant());
+ var conn = new PluginConnection(new StringReader($"-> file-key 0\n{body}\n-> done\n\n"), new StringWriter());
+
+ var ex = Assert.Throws(() => identity.UnwrapWithConnection(conn, [new Stanza("frood", [], [1])]));
+
+ Assert.Equal($"the plugin sent a file key of {size} bytes; a file key is 16 bytes", ex.Message);
+ }
+
+ // --- a plugin author's mistake still ends in an exit code -----------------------------------
+
+ private static readonly string FroodRecipient = Bech32.Encode("age1frood", [1]);
+ private static readonly string FroodIdentity = Bech32.Encode("AGE-PLUGIN-FROOD-", [1]).ToUpperInvariant();
+
+ [Fact]
+ public void AnIdentityHandlerThatReturnsNull_IsThatIdentitysError()
+ {
+ var plugin = new AgePlugin("frood");
+ plugin.HandleIdentity(_ => null!);
+
+ var outcome = InProcessPlugin.Run(plugin, "identity-v1", conn =>
+ {
+ conn.WriteStanza("add-identity", [FroodIdentity], []);
+ conn.WriteStanza("recipient-stanza", ["0", "frood"], [1]);
+ conn.WriteStanza("done", [], []);
+ var reply = conn.ReadStanza();
+ conn.WriteStanza("ok", [], []);
+ return reply;
+ });
+
+ AssertItsError(outcome, "identity");
+ }
+
+ [Fact]
+ public void ARecipientHandlerThatReturnsNull_IsThatRecipientsError()
+ {
+ var plugin = new AgePlugin("frood");
+ plugin.HandleRecipient(_ => null!);
+
+ var outcome = InProcessPlugin.Run(plugin, "recipient-v1", conn =>
+ {
+ conn.WriteStanza("add-recipient", [FroodRecipient], []);
+ conn.WriteStanza("wrap-file-key", [], new byte[16]);
+ conn.WriteStanza("done", [], []);
+ var reply = conn.ReadStanza();
+ conn.WriteStanza("ok", [], []);
+ return reply;
+ });
+
+ AssertItsError(outcome, "recipient");
+ }
+
+ [Fact]
+ public void ARecipientThatWrapsToANullStanza_IsThatRecipientsError()
+ {
+ var plugin = new AgePlugin("frood");
+ plugin.HandleRecipient(_ => new WrapsToNull());
+
+ var outcome = InProcessPlugin.Run(plugin, "recipient-v1", conn =>
+ {
+ conn.WriteStanza("add-recipient", [FroodRecipient], []);
+ conn.WriteStanza("wrap-file-key", [], new byte[16]);
+ conn.WriteStanza("done", [], []);
+ var reply = conn.ReadStanza();
+ conn.WriteStanza("ok", [], []);
+ return reply;
+ });
+
+ AssertItsError(outcome, "recipient");
+ }
+
+ // The plugin told the client which key failed, and exited as go-age's plugins do for one.
+ private static void AssertItsError(InProcessPlugin.Outcome<(string Type, string[] Args, byte[] Body)?> outcome, string kind)
+ {
+ Assert.Null(outcome.ClientFailure);
+ Assert.Equal(3, outcome.ExitCode);
+
+ var reply = Assert.NotNull(outcome.Result);
+ Assert.Equal("error", reply.Type);
+ Assert.Equal([kind, "0"], reply.Args);
+ }
+
+ private sealed class WrapsToNull : IRecipient
+ {
+ public IReadOnlyList Wrap(ReadOnlySpan fileKey) => [null!];
+ }
+}
diff --git a/Age.Tests/SshTests.cs b/Age.Tests/SshTests.cs
index 83a0e1c..ad041fe 100644
--- a/Age.Tests/SshTests.cs
+++ b/Age.Tests/SshTests.cs
@@ -595,8 +595,10 @@ public void RejectsSmallKey()
var wireBytes = OpenSshPublicKeyUtilities.EncodePublicKey(kp.Public);
- Assert.Throws(() =>
- new SshRsaRecipient((RsaKeyParameters)kp.Public, wireBytes));
+ // Refused where it is read; an identity's own recipient is refused when it wraps
+ // (DocumentedExceptionsTests).
+ var ex = Assert.Throws(() => SshRsaRecipient.Parse($"ssh-rsa {Convert.ToBase64String(wireBytes)}"));
+ Assert.Equal("RSA key must be at least 2048 bits, got 1024", ex.Message);
}
[Fact]
diff --git a/Age.Tests/TestData/EncryptedSsh/rsa_1024_aes256ctr b/Age.Tests/TestData/EncryptedSsh/rsa_1024_aes256ctr
new file mode 100644
index 0000000..ccd90a4
--- /dev/null
+++ b/Age.Tests/TestData/EncryptedSsh/rsa_1024_aes256ctr
@@ -0,0 +1,17 @@
+-----BEGIN OPENSSH PRIVATE KEY-----
+b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABDsVt/7Eh
+7FD2fFwvbQ+ADzAAAAGAAAAAEAAACXAAAAB3NzaC1yc2EAAAADAQABAAAAgQCxcHikmV9i
+HMBB+CBgY4FScAT1GgxCIeFVvOoUanFTYJ4SgQtA12hffimq+UgkIWiArMkWu1zEvX7EAc
+dZ1U/KNi/FkLoq6VA6yzXDHS1YBNpIV8WxAnOaa7JpJXlPBrF3L35L8Y1dlDEY4HT6ujBx
+dDCAx88Wx1SbBii/AsA8EQAAAgBVdrSjHK6nKWPedKjrcrcpU3raAfK0ksy9Nh0hJE0MTN
+/2WzMg7viLt2T7JuaHuoB3gYuQVnEYF7uLuBsm4udL4j5pFNLopwJxXPjFuAlDCSuipT0v
+pO9gwQtaEZjh9OGJFHeXhsuQWcaQf/agD7ZervDx24Vje64zK1TWsziUKKYakagtV9fPl3
+pgzlw5oEzwqIseDAT7SASx3MXwv17uaUzC0g8+UWef90G9AYfM/NSn6LHvItE2jvLR/SAR
+1ZjST1Bi0xYOjO7vf4uI6cSpbmaRUfy+pFDbA8Xl6ANC7pVRw+A2QNquMjjwe+VcNMXM9P
+fEYtRMzs4o3yds5GR4bLrAhWId1yvAYcUWh2gSVtUzDgUGKQtkOq4gNjWJ1VfTNsQCq+uy
+uf05UQgTCghPjmYhpGS3290eIN7Pnn0WkE0Yeux3km8O1kcVLHqJFG+29arsXafYGhRi9B
+TfAzJ+nWMf2RfUNsGDC15awry2BzRqqn2jTQAwrJyDwA4Ozn2vi6r8xyylLQuTs7jDbufB
+UPRHBizcdRgEDph/rg7U/bvmjL7IBRs8POAdDLMi9oAKlymzbqVHKhAYtgTI4o41ZYbcCb
+VHH6hrPuTVMfp0XFFD/WYZo/fm2l6HgtH9uFe8GsjiH8mmxE4XxmOAApQFDuLS3VdEzXm1
+cdTRS50KAQ==
+-----END OPENSSH PRIVATE KEY-----
diff --git a/Age/Plugin/AgePlugin.cs b/Age/Plugin/AgePlugin.cs
index 300fae8..5a59990 100644
--- a/Age/Plugin/AgePlugin.cs
+++ b/Age/Plugin/AgePlugin.cs
@@ -295,6 +295,9 @@ private int WrapAll(List recipientStrings, List identityStrings,
if (wrapped.Stanzas is not { Count: > 0 })
return KeyError(kind, index, $"recipient {recipient.GetType().Name} produced no stanzas");
+ if (wrapped.Stanzas.Contains(null!))
+ return KeyError(kind, index, $"recipient {recipient.GetType().Name} produced a null stanza");
+
stanzas[f].AddRange(wrapped.Stanzas);
}
}
@@ -696,7 +699,9 @@ private bool TryParse(string encoded, string kind, int index, Func GetRecipients()
/// The file has been disposed.
public bool TryUnwrap(Stanza stanza, Span fileKey)
{
+ ArgumentNullException.ThrowIfNull(stanza);
+
lock (_lock)
{
foreach (var identity in Unlocked())
diff --git a/Age/Recipients/EncryptedSshIdentity.cs b/Age/Recipients/EncryptedSshIdentity.cs
index 6d01df1..2eb9cdf 100644
--- a/Age/Recipients/EncryptedSshIdentity.cs
+++ b/Age/Recipients/EncryptedSshIdentity.cs
@@ -1,6 +1,7 @@
using System.Security.Cryptography;
using AgeSharp.Crypto;
using AgeSharp;
+using Org.BouncyCastle.Crypto.Parameters;
namespace AgeSharp;
@@ -30,8 +31,13 @@ internal EncryptedSshIdentity(IProtectedSshKey protectedKey, Func passp
_keyType = SshKeyParser.KeyTypeOfWireBytes(protectedKey.PublicKey);
_tag = SshKeyParser.ComputeTag(protectedKey.PublicKey);
- var authorizedKeysLine = $"{_keyType} {Convert.ToBase64String(protectedKey.PublicKey)}";
- _recipient = Recipients.ParseSsh(authorizedKeysLine);
+ var (_, wireBytes, publicKey) = SshKeyParser.ParsePublicKey($"{_keyType} {Convert.ToBase64String(protectedKey.PublicKey)}");
+
+ // An identity's recipient, so an RSA key of any size has one, as SshRsaIdentity's has:
+ // go-age decrypts with a small RSA key, protected or not, and refuses only to wrap to it.
+ _recipient = publicKey is Ed25519PublicKeyParameters ed25519
+ ? SshEd25519Recipient.From(wireBytes, ed25519)
+ : new SshRsaRecipient((RsaKeyParameters)publicKey, wireBytes);
}
private readonly IRecipient _recipient;
diff --git a/Age/Recipients/FileKeyIdentity.cs b/Age/Recipients/FileKeyIdentity.cs
index c8ad426..4eb50df 100644
--- a/Age/Recipients/FileKeyIdentity.cs
+++ b/Age/Recipients/FileKeyIdentity.cs
@@ -27,6 +27,8 @@ public FileKeyIdentity(FileKey fileKey)
/// The identity has been disposed.
public bool TryUnwrap(Stanza stanza, Span fileKey)
{
+ ArgumentNullException.ThrowIfNull(stanza);
+
var key = _fileKey.Bytes;
if (fileKey.Length != FileKey.Size)
diff --git a/Age/Recipients/IIdentity.cs b/Age/Recipients/IIdentity.cs
index 830b2ae..06d280e 100644
--- a/Age/Recipients/IIdentity.cs
+++ b/Age/Recipients/IIdentity.cs
@@ -51,6 +51,8 @@ void IDisposable.Dispose()
///
bool TryUnwrap(IReadOnlyList stanzas, Span fileKey)
{
+ ArgumentNullException.ThrowIfNull(stanzas);
+
foreach (var stanza in stanzas)
{
if (TryUnwrap(stanza, fileKey))
diff --git a/Age/Recipients/MlKem768P256TagRecipient.cs b/Age/Recipients/MlKem768P256TagRecipient.cs
index 623fbc1..9dc0f52 100644
--- a/Age/Recipients/MlKem768P256TagRecipient.cs
+++ b/Age/Recipients/MlKem768P256TagRecipient.cs
@@ -30,6 +30,8 @@ private MlKem768P256TagRecipient(byte[] publicKey) =>
/// The string is not a valid tagged post-quantum recipient.
public static MlKem768P256TagRecipient Parse(string s)
{
+ ArgumentNullException.ThrowIfNull(s);
+
var (hrp, data) = Bech32.Decode(s);
if (hrp != Hrp)
diff --git a/Age/Recipients/MlKem768X25519Identity.cs b/Age/Recipients/MlKem768X25519Identity.cs
index fc7c090..9d5f097 100644
--- a/Age/Recipients/MlKem768X25519Identity.cs
+++ b/Age/Recipients/MlKem768X25519Identity.cs
@@ -53,6 +53,8 @@ public static MlKem768X25519Identity Generate()
/// The string is not a valid ML-KEM-768-X25519 secret key.
public static MlKem768X25519Identity Parse(string s)
{
+ ArgumentNullException.ThrowIfNull(s);
+
if (s != s.ToUpperInvariant())
throw new FormatException("age secret key must be uppercase");
@@ -116,6 +118,7 @@ public bool TryUnwrap(Stanza stanza, Span fileKey) =>
// The file key is never in an array of ours: it is decrypted on the stack.
private bool UnwrapInto(Stanza stanza, Span fileKey)
{
+ ArgumentNullException.ThrowIfNull(stanza);
FileKey.RequireBuffer(fileKey);
ObjectDisposedException.ThrowIf(_disposed, this);
diff --git a/Age/Recipients/MlKem768X25519Recipient.cs b/Age/Recipients/MlKem768X25519Recipient.cs
index 2807eeb..772bebd 100644
--- a/Age/Recipients/MlKem768X25519Recipient.cs
+++ b/Age/Recipients/MlKem768X25519Recipient.cs
@@ -29,6 +29,8 @@ internal MlKem768X25519Recipient(byte[] publicKey)
/// The string is not a valid ML-KEM-768-X25519 recipient.
public static MlKem768X25519Recipient Parse(string s)
{
+ ArgumentNullException.ThrowIfNull(s);
+
var (hrp, data) = Bech32.Decode(s);
if (hrp != Hrp)
diff --git a/Age/Recipients/P256TagRecipient.cs b/Age/Recipients/P256TagRecipient.cs
index 226c01f..d0045f1 100644
--- a/Age/Recipients/P256TagRecipient.cs
+++ b/Age/Recipients/P256TagRecipient.cs
@@ -32,6 +32,8 @@ private P256TagRecipient(byte[] compressedPoint, byte[] point)
/// The string is not a valid tagged P-256 recipient.
public static P256TagRecipient Parse(string s)
{
+ ArgumentNullException.ThrowIfNull(s);
+
var (hrp, data) = Bech32.Decode(s);
if (hrp != Hrp)
diff --git a/Age/Recipients/Passphrase.cs b/Age/Recipients/Passphrase.cs
index d403748..a9d8e4b 100644
--- a/Age/Recipients/Passphrase.cs
+++ b/Age/Recipients/Passphrase.cs
@@ -159,6 +159,7 @@ public bool TryUnwrap(Stanza stanza, Span fileKey) =>
// The file key is never in an array of ours: it is decrypted on the stack.
private bool UnwrapInto(Stanza stanza, Span fileKey)
{
+ ArgumentNullException.ThrowIfNull(stanza);
FileKey.RequireBuffer(fileKey);
if (stanza.Type != StanzaType)
diff --git a/Age/Recipients/PluginIdentity.cs b/Age/Recipients/PluginIdentity.cs
index 0c325ce..8a34017 100644
--- a/Age/Recipients/PluginIdentity.cs
+++ b/Age/Recipients/PluginIdentity.cs
@@ -56,8 +56,11 @@ public static PluginIdentity Parse(string s, IPluginCallbacks? plugins = null)
/// Tries to unwrap a single stanza by running the plugin binary.
/// The plugin failed, misbehaved, or reported an internal error.
- public bool TryUnwrap(Stanza stanza, Span fileKey) =>
- TryUnwrap([stanza], fileKey);
+ public bool TryUnwrap(Stanza stanza, Span fileKey)
+ {
+ ArgumentNullException.ThrowIfNull(stanza);
+ return TryUnwrap([stanza], fileKey);
+ }
///
/// Tries to unwrap any of the stanzas in a single plugin session — one
@@ -66,6 +69,8 @@ public bool TryUnwrap(Stanza stanza, Span fileKey) =>
/// The plugin failed, misbehaved, or reported an internal error.
public bool TryUnwrap(IReadOnlyList stanzas, Span fileKey)
{
+ ArgumentNullException.ThrowIfNull(stanzas);
+
using var conn = new PluginConnection(PluginName, "identity-v1");
return FileKey.Deliver(UnwrapWithConnection(conn, stanzas), fileKey);
}
@@ -111,6 +116,11 @@ private void SendUnwrapRequest(PluginConnection conn, IReadOnlyList stan
if (result is not null)
throw new AgePluginException("duplicate file-key stanza");
+ // The plugin's mistake, so said here: left to the caller's buffer it would
+ // come out as a malformed file.
+ if (body.Length != FileKey.Size)
+ throw new AgePluginException($"the plugin sent a file key of {body.Length} bytes; a file key is {FileKey.Size} bytes");
+
result = body;
conn.WriteStanza("ok", [], []);
break;
diff --git a/Age/Recipients/SshEd25519Identity.cs b/Age/Recipients/SshEd25519Identity.cs
index 275d323..3727a70 100644
--- a/Age/Recipients/SshEd25519Identity.cs
+++ b/Age/Recipients/SshEd25519Identity.cs
@@ -45,6 +45,8 @@ public SshEd25519Recipient Recipient
/// The text is not a valid ssh-ed25519 private key.
public static SshEd25519Identity Parse(string pemText)
{
+ ArgumentNullException.ThrowIfNull(pemText);
+
var (keyType, publicWireBytes, privateKey) = SshKeyParser.ParsePrivateKey(pemText);
return FromParsedKey(keyType, publicWireBytes, privateKey);
}
@@ -93,6 +95,7 @@ public bool TryUnwrap(Stanza stanza, Span fileKey) =>
// The file key is never in an array of ours: it is decrypted on the stack.
private bool UnwrapInto(Stanza stanza, Span fileKey)
{
+ ArgumentNullException.ThrowIfNull(stanza);
FileKey.RequireBuffer(fileKey);
ObjectDisposedException.ThrowIf(_disposed, this);
diff --git a/Age/Recipients/SshEd25519Recipient.cs b/Age/Recipients/SshEd25519Recipient.cs
index 241b496..75cc5fe 100644
--- a/Age/Recipients/SshEd25519Recipient.cs
+++ b/Age/Recipients/SshEd25519Recipient.cs
@@ -34,6 +34,8 @@ internal SshEd25519Recipient(byte[] sshWireBytes, byte[] x25519PublicKey)
/// The line is not a valid ssh-ed25519 public key.
public static SshEd25519Recipient Parse(string authorizedKeysLine)
{
+ ArgumentNullException.ThrowIfNull(authorizedKeysLine);
+
var (keyType, wireBytes, pubKey) = SshKeyParser.ParsePublicKey(authorizedKeysLine);
if (keyType != "ssh-ed25519")
diff --git a/Age/Recipients/SshIdentity.cs b/Age/Recipients/SshIdentity.cs
index 546ce49..5f72e96 100644
--- a/Age/Recipients/SshIdentity.cs
+++ b/Age/Recipients/SshIdentity.cs
@@ -27,6 +27,8 @@ public static class SshIdentity
///
public static IIdentity Parse(string pemText)
{
+ ArgumentNullException.ThrowIfNull(pemText);
+
var (keyType, publicWireBytes, privateKey) = SshKeyParser.ParsePrivateKey(pemText);
return keyType switch
diff --git a/Age/Recipients/SshRsaIdentity.cs b/Age/Recipients/SshRsaIdentity.cs
index 9be715b..0bf8c8a 100644
--- a/Age/Recipients/SshRsaIdentity.cs
+++ b/Age/Recipients/SshRsaIdentity.cs
@@ -48,6 +48,8 @@ public SshRsaRecipient Recipient
/// The text is not a valid ssh-rsa private key.
public static SshRsaIdentity Parse(string pemText)
{
+ ArgumentNullException.ThrowIfNull(pemText);
+
var (keyType, publicWireBytes, privateKey) = SshKeyParser.ParsePrivateKey(pemText);
return FromParsedKey(keyType, publicWireBytes, privateKey);
}
@@ -73,6 +75,7 @@ public bool TryUnwrap(Stanza stanza, Span fileKey) =>
private byte[]? UnwrapToArray(Stanza stanza)
{
+ ArgumentNullException.ThrowIfNull(stanza);
ObjectDisposedException.ThrowIf(_disposed, this);
if (stanza.Type != AgeProtocol.SshRsaStanzaType)
diff --git a/Age/Recipients/SshRsaRecipient.cs b/Age/Recipients/SshRsaRecipient.cs
index f0ea137..cc804d4 100644
--- a/Age/Recipients/SshRsaRecipient.cs
+++ b/Age/Recipients/SshRsaRecipient.cs
@@ -21,11 +21,11 @@ public sealed class SshRsaRecipient : IRecipient
private readonly byte[] _sshWireBytes;
private readonly string _tag;
+ // No size check here: an identity of any size has a recipient, as in go-age, whose
+ // RSAIdentity.Recipient builds one unchecked. A key read as a recipient is checked by From,
+ // and every key again by Wrap.
internal SshRsaRecipient(RsaKeyParameters publicKey, byte[] sshWireBytes)
{
- if (publicKey.Modulus.BitLength < MinKeyBits)
- throw new ArgumentException($"RSA key must be at least {MinKeyBits} bits, got {publicKey.Modulus.BitLength}");
-
_publicKey = publicKey;
_sshWireBytes = sshWireBytes;
_tag = SshKeyParser.ComputeTag(sshWireBytes);
@@ -38,6 +38,8 @@ internal SshRsaRecipient(RsaKeyParameters publicKey, byte[] sshWireBytes)
/// The line is not a valid ssh-rsa public key.
public static SshRsaRecipient Parse(string authorizedKeysLine)
{
+ ArgumentNullException.ThrowIfNull(authorizedKeysLine);
+
var (keyType, wireBytes, pubKey) = SshKeyParser.ParsePublicKey(authorizedKeysLine);
if (keyType != "ssh-rsa")
@@ -50,20 +52,29 @@ public static SshRsaRecipient Parse(string authorizedKeysLine)
/// The key is smaller than 2048 bits.
internal static SshRsaRecipient From(byte[] wireBytes, RsaKeyParameters publicKey)
{
- // Checked here as well as in the constructor, so a small key read from text is a format
- // error rather than the constructor's ArgumentException.
if (publicKey.Modulus.BitLength < MinKeyBits)
- throw new FormatException($"RSA key must be at least {MinKeyBits} bits, got {publicKey.Modulus.BitLength}");
+ throw new FormatException(TooSmall(publicKey));
return new SshRsaRecipient(publicKey, wireBytes);
}
/// Wraps the file key for this SSH key using RSA-OAEP (SHA-256).
+ ///
+ /// The key is smaller than 2048 bits. Only the recipient of an identity can be: one that is
+ /// parsed is refused then. As go-age, AgeSharp decrypts with such a key and does not
+ /// encrypt to it.
+ ///
public IReadOnlyList Wrap(ReadOnlySpan fileKey) =>
[WrapOne(fileKey)];
+ private static string TooSmall(RsaKeyParameters key) =>
+ $"RSA key must be at least {MinKeyBits} bits, got {key.Modulus.BitLength}";
+
private Stanza WrapOne(ReadOnlySpan fileKey)
{
+ if (_publicKey.Modulus.BitLength < MinKeyBits)
+ throw new AgeException(TooSmall(_publicKey));
+
var oaep = new OaepEncoding(new RsaBlindedEngine(), new Sha256Digest(), new Sha256Digest(), Encoding.ASCII.GetBytes(AgeProtocol.SshRsaOaepLabel));
oaep.Init(true, _publicKey);
diff --git a/Age/Recipients/X25519Identity.cs b/Age/Recipients/X25519Identity.cs
index 2b8c657..53677f7 100644
--- a/Age/Recipients/X25519Identity.cs
+++ b/Age/Recipients/X25519Identity.cs
@@ -62,6 +62,8 @@ public static X25519Identity Generate()
/// The string is not a valid X25519 secret key.
public static X25519Identity Parse(string s)
{
+ ArgumentNullException.ThrowIfNull(s);
+
if (s != s.ToUpperInvariant())
throw new FormatException("age secret key must be uppercase");
@@ -122,6 +124,7 @@ public bool TryUnwrap(Stanza stanza, Span fileKey) =>
// The file key is never in an array of ours: it is decrypted on the stack.
private bool UnwrapInto(Stanza stanza, Span fileKey)
{
+ ArgumentNullException.ThrowIfNull(stanza);
FileKey.RequireBuffer(fileKey);
ObjectDisposedException.ThrowIf(_disposed, this);
diff --git a/Age/Recipients/X25519Recipient.cs b/Age/Recipients/X25519Recipient.cs
index 9e2b87c..6bdb2ca 100644
--- a/Age/Recipients/X25519Recipient.cs
+++ b/Age/Recipients/X25519Recipient.cs
@@ -27,6 +27,8 @@ internal X25519Recipient(X25519PublicKeyParameters publicKey)
/// The string is not a valid X25519 recipient.
public static X25519Recipient Parse(string s)
{
+ ArgumentNullException.ThrowIfNull(s);
+
var (hrp, data) = Bech32.Decode(s);
if (hrp != Hrp)
diff --git a/TODO.md b/TODO.md
index 26e8de8..a79e33a 100644
--- a/TODO.md
+++ b/TODO.md
@@ -49,7 +49,7 @@ The rebuild is done and the public API frozen (rebuild step 8d): `PublicAPI.Ship
the surface as frozen, and any change to it from here is a breaking change. Additions since
(`AgePlugin`, `PluginIdentity.Recipient`) are in `PublicAPI.Unshipped.txt` until a release.
-- [ ] Release notes for the next release, on behaviour changed since the freeze: a payload cut off in its nonce is now `AgeAuthenticationException` (was `AgeFormatException`), as Decrypt documented; a wrong passphrase for an `EncryptedIdentityFile` or a protected SSH key is `AgeAuthenticationException` (was the base `AgeException`, so `catch (AgeException)` still catches it); the SSH identities' `Recipient` throws `ObjectDisposedException` after `Dispose`, as the interface says; an `EncryptedIdentityFile` whose decrypted contents are not an identity file is `AgeFormatException` (was a raw `FormatException`); and, as go-age decides them, an indented armor begin line and non-ASCII in a Bech32 key are refused, an `ssh-ed25519` stanza's share is checked before its tag, and one whose body is not 32 bytes is no match rather than an error; `AgePlugin` refuses a labelled recipient for a client without label support, and takes `unsupported` as a refusal, as rage does; from the 2026-11-30 review: `Recipients.Parse` names a line that is no recipient by its number and no longer repeats it (`ParseOne` still names its argument), and a protected SSH key that decrypts to something unusable says only that, with no text and no inner exception from SSH.NET (a wrong passphrase for a legacy PEM key carries no inner exception either); text an error repeats from a file, a key or a plugin is quoted and cut to a length (`unexpected line in header: "…"`), a plugin's error message and stderr have their control characters written out, a byte in an armor body that is not base64 is named by its value (`0xE9`, was `'?'`), and `NoIdentityMatchException.Message` shows at most eight stanza types of 32 characters each (`StanzaTypes` holds them whole)
+- [ ] Release notes for the next release, on behaviour changed since the freeze: a payload cut off in its nonce is now `AgeAuthenticationException` (was `AgeFormatException`), as Decrypt documented; a wrong passphrase for an `EncryptedIdentityFile` or a protected SSH key is `AgeAuthenticationException` (was the base `AgeException`, so `catch (AgeException)` still catches it); the SSH identities' `Recipient` throws `ObjectDisposedException` after `Dispose`, as the interface says; an `EncryptedIdentityFile` whose decrypted contents are not an identity file is `AgeFormatException` (was a raw `FormatException`); and, as go-age decides them, an indented armor begin line and non-ASCII in a Bech32 key are refused, an `ssh-ed25519` stanza's share is checked before its tag, and one whose body is not 32 bytes is no match rather than an error; `AgePlugin` refuses a labelled recipient for a client without label support, and takes `unsupported` as a refusal, as rage does; from the 2026-11-30 review: `Recipients.Parse` names a line that is no recipient by its number and no longer repeats it (`ParseOne` still names its argument), and a protected SSH key that decrypts to something unusable says only that, with no text and no inner exception from SSH.NET (a wrong passphrase for a legacy PEM key carries no inner exception either); text an error repeats from a file, a key or a plugin is quoted and cut to a length (`unexpected line in header: "…"`), a plugin's error message and stderr have their control characters written out, a byte in an armor body that is not base64 is named by its value (`0xE9`, was `'?'`), and `NoIdentityMatchException.Message` shows at most eight stanza types of 32 characters each (`StanzaTypes` holds them whole); a null argument to a `Parse` method or to `TryUnwrap` is an `ArgumentNullException` everywhere (ten parsers and every identity threw `NullReferenceException`); an SSH RSA identity under 2048 bits has a `Recipient`, and encrypting to it is an `AgeException` (the property threw `ArgumentException`), and a passphrase-protected one now parses and decrypts (it was refused when read), as go-age decrypts with both; a file key of the wrong size from a plugin is `AgePluginException` (was `AgeFormatException`); an `AgePlugin` handler that returns null, or a recipient that wraps to a null stanza, is that key's error and exit code 3 (was an exception out of `Run`)
- [x] Async entry points for encrypt and decrypt: `EncryptAsync`, `DecryptAsync`, `DecryptReaderAsync`, the detached forms and the writers (rebuild steps 4b to 4d)
- [x] Before the freeze, a review of the whole surface: plugin callbacks name the plugin and may decline, `PluginRecipient.Parse`/`PluginIdentity.Parse`, plugin labels, one `Func` shape for passphrase sources (rebuild steps 8a to 8c)
- [x] Peeking armor detection, so armored input is recognised on non-seekable streams too (pipes, network streams) — rebuild step 3c: `PeekableStream`; `Decrypt`, `DecryptReader` and `AgeHeader.Read` read ahead instead of seeking