Recursive AI

Prepare and complete a detached signature in C#

OneCrypto is a free, open-source cryptography library for .NET from Recursive AI. MIT or Apache-2.0, preview, no native dependencies.

Two-phase signing separates preparing the bytes to sign from accepting the returned signature. This example runs both sides locally with a software RSA key.

Terminal
dotnet add package RecursiveAI.OneCrypto --prerelease

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using System.Security.Cryptography;
using RecursiveAI.OneCrypto.Keys;
using RecursiveAI.OneCrypto.Policy;
 
using var rsa = RSA.Create(2048);
using var key = PrivateKey.FromRsa(rsa);
var spec = SignatureSpec.RsaPkcs1(HashAlgorithmName.SHA256);
// Preparer side: prepare the request.
var state = PreparedSignature.Prepare(key.PublicKey,
    spec, "hello"u8, CryptoPolicy.Standard,
    DateTimeOffset.UtcNow);
// Signer side: may run elsewhere with the private key.
var decoded = PreparedSignature.Decode(state.Encode());
byte[] signature = key.SignDigest(
    decoded.ToSign.Span, decoded.Spec);
// Preparer side: verify and accept the returned signature.
byte[] completed = state.Complete(signature);
Console.WriteLine(state.Verify(completed).IsValid);
Text
True

Unzip the example, then dotnet run.

The full program

The program also rejects a modified result.

C#
using System.Security.Cryptography;
using RecursiveAI.OneCrypto.Keys;
using RecursiveAI.OneCrypto.Policy;
 
using var rsa = RSA.Create(2048);
using var key = PrivateKey.FromRsa(rsa);
var spec = SignatureSpec.RsaPkcs1(HashAlgorithmName.SHA256);
var state = PreparedSignature.Prepare(key.PublicKey,
    spec, "hello"u8, CryptoPolicy.Standard,
    DateTimeOffset.UtcNow);
var decoded = PreparedSignature.Decode(state.Encode());
byte[] signature = key.SignDigest(
    decoded.ToSign.Span, decoded.Spec);
byte[] completed = state.Complete(signature);
Console.WriteLine(state.Verify(completed).IsValid);
Console.WriteLine($"Signature: {completed.Length} bytes");
completed[0] ^= 1;
Console.WriteLine($"Modified accepted: {state.TryComplete(completed, out _, out _)}");
Text
True
Signature: 256 bytes
Modified accepted: False

Complete throws InvalidSignatureException if the signature does not verify against the prepared state.

Variations

Use RSA-PSS instead of PKCS #1 v1.5.

C#
using System.Security.Cryptography;
using RecursiveAI.OneCrypto.Keys;
using RecursiveAI.OneCrypto.Policy;
 
using var rsa = RSA.Create(2048);
using var key = PrivateKey.FromRsa(rsa);
var spec = SignatureSpec.RsaPss(HashAlgorithmName.SHA256);
var state = PreparedSignature.Prepare(key.PublicKey,
    spec, "hello"u8, CryptoPolicy.Standard,
    DateTimeOffset.UtcNow);
var decoded = PreparedSignature.Decode(state.Encode());
byte[] signature = key.SignDigest(
    decoded.ToSign.Span, decoded.Spec);
byte[] completed = state.Complete(signature);
Console.WriteLine(state.Verify(completed).IsValid);
Text
True

The short answer

Use PreparedSignature.Prepare, serialize with Encode, sign the decoded request’s ToSign under its Spec, then call Complete on the original state. This produces a raw detached signature, not a CMS or PDF container.

How do I prepare a signature in two phases in C#?

Use PreparedSignature.Prepare with the signer’s public key, a signature specification, the original message, a policy and the signing time. This creates the request, not the signature. For RSA and ECDSA, ToSign holds a digest; for the message-signing schemes it holds the message. The key documentation defines that distinction explicitly.

The example chooses RSA with PKCS #1 v1.5 and SHA-256. It DER-encodes the prepared request and decodes it again to exercise the boundary between the preparer and signer. It uses a local key for the signing operation; there is no remote endpoint or hardware dependency hidden in the sample.

After signing, send the raw signature back to the original preparer. Complete verifies it against the recorded key and data before returning a copy. Keep that original state for completion rather than trusting a replacement state supplied with the returned signature.

What does a detached digital signature look like?

Here it is a byte array separate from the original hello message. The example’s RSA signature is 256 bytes because its RSA key is 2048 bits. Those bytes are not a CMS document, a PDF signature or a certificate. Encoding a prepared request also does not turn the result into any of those containers.

The prepared state carries more information than the finished signature: the public key, scheme, purpose, input kind and bytes to sign, plus the original data when available. The documented DER structure has an explicit version. Treat it as a request format for this API, not a universal remote-signing protocol.

The verifier still needs the matching public key, scheme and message when using the raw signature outside this state. Keep message bytes unchanged; text encoding and newline conversions can produce a different message even when it looks the same on screen.

How do I sign the prepared digest without hashing it twice?

For the RSA example, call SignDigest with decoded.ToSign.Span and decoded.Spec, as the full program does. Calling Sign there would hash the digest as though it were a fresh message. That is not the operation the preparer requested, so completion would fail.

For an input you have already hashed, PrepareDigest is available for RSA and ECDSA. The digest must have the length required by the chosen hash. Message-signing schemes instead need Prepare; a digest-only request cannot stand in for their message. Choose this boundary before building the signer’s transport, rather than guessing from the size of ToSign.

Can a prepared signature be completed with the wrong signature?

No. Completion checks the returned bytes. The full program flips a bit in a completed signature, then TryComplete returns False. That overload provides the verification result without throwing; the throwing form exposes it through InvalidSignatureException.Result.

Preparation also checks policy before creating the state. A policy rejection raises PolicyViolationException, and an incompatible key and scheme raises an argument error. A purpose label records the intended use, but it does not create a signed document container. Use a format-specific signing API when the final artifact must be CMS, X.509 or PDF rather than a raw detached signature.

All onecrypto recipes