Path: redb-route/redb.Route.As2/Crypto/As2CryptoEngine.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/Crypto/As2CryptoEngine.cs ---- using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using MimeKit; using MimeKit.Cryptography; namespace redb.Route.As2.Crypto; /// /// Default AS2 crypto engine, built on MimeKit's S/MIME support (Bouncy Castle underneath) — the same /// cryptographic foundation the AS2 industry (camel-as2, OpenAS2, Mendelson) interoperates on. /// Uses an in-memory per operation with the relevant certificate /// imported, so no on-disk certificate store is required. /// internal sealed class As2CryptoEngine : IAs2CryptoEngine { /// public MultipartSigned Sign(MimeEntity content, X509Certificate2 signerCert, string micalg) { ArgumentNullException.ThrowIfNull(content); ArgumentNullException.ThrowIfNull(signerCert); if (!signerCert.HasPrivateKey) throw new ArgumentException("Signing certificate must have a private key.", nameof(signerCert)); using var ctx = new TemporarySecureMimeContext(); var signer = new CmsSigner(signerCert) { DigestAlgorithm = MapDigest(micalg) }; return MultipartSigned.Create(ctx, signer, content); } /// public MimeEntity Encrypt(MimeEntity content, X509Certificate2 recipientCert, string encAlg) { ArgumentNullException.ThrowIfNull(content); ArgumentNullException.ThrowIfNull(recipientCert); using var ctx = new TemporarySecureMimeContext(); var recipient = new CmsRecipient(recipientCert) { EncryptionAlgorithms = [MapEncryption(encAlg)] }; return ApplicationPkcs7Mime.Encrypt(ctx, new CmsRecipientCollection { recipient }, content); } /// public MimeEntity Compress(MimeEntity content) { ArgumentNullException.ThrowIfNull(content); using var ctx = new TemporarySecureMimeContext(); return ApplicationPkcs7Mime.Compress(ctx, content); } /// public MimeEntity Decrypt(MimeEntity encrypted, X509Certificate2 ourCert) { ArgumentNullException.ThrowIfNull(encrypted); ArgumentNullException.ThrowIfNull(ourCert); if (encrypted is not ApplicationPkcs7Mime { SecureMimeType: SecureMimeType.EnvelopedData } pkcs7) throw new ArgumentException("Entity is not S/MIME enveloped-data.", nameof(encrypted)); using var ctx = new TemporarySecureMimeContext(); ctx.Import(ourCert); return pkcs7.Decrypt(ctx); } /// public void DecryptTo(ApplicationPkcs7Mime encrypted, X509Certificate2 ourCert, Stream output) { ArgumentNullException.ThrowIfNull(encrypted); ArgumentNullException.ThrowIfNull(ourCert); ArgumentNullException.ThrowIfNull(output); if (encrypted.SecureMimeType != SecureMimeType.EnvelopedData || encrypted.Content is null) throw new ArgumentException("Entity is not S/MIME enveloped-data.", nameof(encrypted)); using var ctx = new TemporarySecureMimeContext(); ctx.Import(ourCert); using var der = encrypted.Content.Open(); // the transfer encoding (base64) removed ctx.DecryptTo(der, output); } /// public void DecompressTo(ApplicationPkcs7Mime compressed, Stream output) { ArgumentNullException.ThrowIfNull(compressed); ArgumentNullException.ThrowIfNull(output); if (compressed.SecureMimeType != SecureMimeType.CompressedData || compressed.Content is null) throw new ArgumentException("Entity is not S/MIME compressed-data.", nameof(compressed)); using var ctx = new TemporarySecureMimeContext(); using var der = compressed.Content.Open(); ctx.DecompressTo(der, output); } /// public bool Verify(MultipartSigned signed, X509Certificate2 signerCert) { ArgumentNullException.ThrowIfNull(signed); ArgumentNullException.ThrowIfNull(signerCert); using var ctx = new TemporarySecureMimeContext(); ctx.Import(signerCert); try { var signatures = signed.Verify(ctx); if (signatures.Count == 0) return false; foreach (var signature in signatures) { // The signature must be cryptographically valid AND made by the expected partner // certificate — an S/MIME signature embeds its own signer cert, so crypto validity alone // does not prove *who* signed. Bind it to signerCert by fingerprint. if (!signature.Verify(verifySignatureOnly: true)) return false; var fingerprint = signature.SignerCertificate?.Fingerprint; if (fingerprint is null || !FingerprintMatches(fingerprint, signerCert)) return false; } return true; } catch (DigitalSignatureVerifyException) { return false; } } /// public MimeEntity Decompress(MimeEntity compressed) { ArgumentNullException.ThrowIfNull(compressed); if (compressed is not ApplicationPkcs7Mime { SecureMimeType: SecureMimeType.CompressedData } pkcs7) throw new ArgumentException("Entity is not S/MIME compressed-data.", nameof(compressed)); using var ctx = new TemporarySecureMimeContext(); return pkcs7.Decompress(ctx); } /// public As2Mic ComputeReceivedMic(MimeEntity part, string micalg) { ArgumentNullException.ThrowIfNull(part); using var hasher = CreateHash(micalg); using (var stream = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write, leaveOpen: true)) { // No Prepare: that would re-encode a binary part (as OpenAS2 signs it) to base64 before it is hashed. The // part was parsed from the wire, so its headers and content are written back as they came, with CRLF line // ends as on the wire: FormatOptions.Default takes the platform's, LF on Linux, and the MIC would differ. part.WriteTo(CrlfFormat, stream); } return new As2Mic(Convert.ToBase64String(hasher.Hash!), NormalizeAlg(micalg)); } /// public As2Mic ComputeMic(MimeEntity part, string micalg, bool includeHeaders) { ArgumentNullException.ThrowIfNull(part); // Hashed as it is written: the content is never copied into memory to be hashed (a received one may be spooled). using var hasher = CreateHash(micalg); using (var stream = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write, leaveOpen: true)) { if (includeHeaders) { // Signed / encrypted: hash the MIME headers + content, CRLF-canonicalized (RFC 4130 §7.3.1). part.Prepare(EncodingConstraint.SevenBit); part.WriteTo(CrlfFormat, stream); } else if (part is MimePart { Content: not null } mp) { // Plain: hash the decoded content only, without MIME headers. mp.Content.DecodeTo(stream); } else { part.WriteTo(CrlfFormat, stream); } } return new As2Mic(Convert.ToBase64String(hasher.Hash!), NormalizeAlg(micalg)); } /// MIME written with CRLF line ends on every platform, as on the wire (RFC 4130 §7.3.1). private static readonly FormatOptions CrlfFormat = CreateCrlfFormat(); private static FormatOptions CreateCrlfFormat() { var options = FormatOptions.Default.Clone(); options.NewLineFormat = NewLineFormat.Dos; return options; } /// /// True if MimeKit's signer fingerprint matches . MimeKit reports the SHA-1 /// fingerprint as hex; .NET's is the same SHA-1 hash in a /// different case, so we normalize both to lowercase hex (and fall back to hashing the raw cert). /// private static bool FingerprintMatches(string mimeKitFingerprint, X509Certificate2 cert) { static string Norm(string s) => string.Concat(s.Where(Uri.IsHexDigit)).ToLowerInvariant(); var actual = Norm(mimeKitFingerprint); if (actual == Norm(cert.Thumbprint)) return true; var sha1 = Convert.ToHexString(cert.GetCertHash(HashAlgorithmName.SHA1)).ToLowerInvariant(); return actual == sha1; } /// Whether is a signature digest this engine supports. public static bool IsSupportedDigest(string alg) => Normalize(alg) is "sha-256" or "sha-1" or "sha-384" or "sha-512"; /// Whether is an encryption algorithm this engine supports. public static bool IsSupportedEncryption(string alg) => alg.ToLowerInvariant() is "aes-128-cbc" or "aes128" or "aes-192-cbc" or "aes192" or "aes-256-cbc" or "aes256" or "3des" or "des-ede3-cbc"; // ── Algorithm mapping ──────────────────────────────────────────────────── private static DigestAlgorithm MapDigest(string micalg) => Normalize(micalg) switch { "sha-256" => DigestAlgorithm.Sha256, "sha-1" => DigestAlgorithm.Sha1, "sha-384" => DigestAlgorithm.Sha384, "sha-512" => DigestAlgorithm.Sha512, _ => throw new NotSupportedException($"Unsupported signature digest algorithm '{micalg}'."), }; private static EncryptionAlgorithm MapEncryption(string alg) => alg.ToLowerInvariant() switch { "aes-128-cbc" or "aes128" => EncryptionAlgorithm.Aes128, "aes-192-cbc" or "aes192" => EncryptionAlgorithm.Aes192, "aes-256-cbc" or "aes256" => EncryptionAlgorithm.Aes256, "3des" or "des-ede3-cbc" => EncryptionAlgorithm.TripleDes, _ => throw new NotSupportedException($"Unsupported encryption algorithm '{alg}'."), }; private static HashAlgorithm CreateHash(string micalg) => Normalize(micalg) switch { "sha-256" => SHA256.Create(), "sha-1" => SHA1.Create(), "sha-384" => SHA384.Create(), "sha-512" => SHA512.Create(), _ => throw new NotSupportedException($"Unsupported MIC algorithm '{micalg}'."), }; /// Canonical AS2 micalg spelling (e.g. sha-256). private static string NormalizeAlg(string micalg) => Normalize(micalg); private static string Normalize(string alg) => alg.ToLowerInvariant() switch { "sha256" or "sha-256" => "sha-256", "sha1" or "sha-1" => "sha-1", "sha384" or "sha-384" => "sha-384", "sha512" or "sha-512" => "sha-512", _ => alg.ToLowerInvariant(), }; }