| | | 1 | | using System.Net; |
| | | 2 | | using System.Security; |
| | | 3 | | using System.Security.Cryptography; |
| | | 4 | | using System.Security.Cryptography.X509Certificates; |
| | | 5 | | using Org.BouncyCastle.Asn1; |
| | | 6 | | using Org.BouncyCastle.Asn1.Pkcs; |
| | | 7 | | using Org.BouncyCastle.Asn1.X509; |
| | | 8 | | using Org.BouncyCastle.Crypto; |
| | | 9 | | using Org.BouncyCastle.Crypto.Generators; |
| | | 10 | | using Org.BouncyCastle.Crypto.Operators; |
| | | 11 | | using Org.BouncyCastle.Crypto.Parameters; |
| | | 12 | | using Org.BouncyCastle.Crypto.Prng; |
| | | 13 | | using Org.BouncyCastle.Math; |
| | | 14 | | using Org.BouncyCastle.OpenSsl; |
| | | 15 | | using Org.BouncyCastle.Pkcs; |
| | | 16 | | using Org.BouncyCastle.Security; |
| | | 17 | | using Org.BouncyCastle.Utilities; |
| | | 18 | | using Org.BouncyCastle.X509; |
| | | 19 | | using System.Text; |
| | | 20 | | using Org.BouncyCastle.Asn1.X9; |
| | | 21 | | using Serilog; |
| | | 22 | | using Kestrun.Utilities; |
| | | 23 | | using System.Text.Json; |
| | | 24 | | using Microsoft.IdentityModel.Tokens; |
| | | 25 | | using System.Security.Claims; |
| | | 26 | | using Microsoft.IdentityModel.JsonWebTokens; |
| | | 27 | | using System.Text.Json.Serialization; |
| | | 28 | | |
| | | 29 | | namespace Kestrun.Certificates; |
| | | 30 | | |
| | | 31 | | /// <summary> |
| | | 32 | | /// Drop-in replacement for Pode’s certificate helpers, powered by Bouncy Castle. |
| | | 33 | | /// </summary> |
| | | 34 | | public static class CertificateManager |
| | | 35 | | { |
| | | 36 | | /// <summary> |
| | | 37 | | /// Controls whether the private key is appended to the certificate PEM file in addition to |
| | | 38 | | /// writing a separate .key file. Appending was initially added to work around platform |
| | | 39 | | /// inconsistencies when importing encrypted PEM pairs on some Linux runners. However, having |
| | | 40 | | /// both a combined (cert+key) file and a separate key file can itself introduce ambiguity in |
| | | 41 | | /// which API path <see cref="X509Certificate2"/> chooses (single-file vs dual-file), which was |
| | | 42 | | /// observed to contribute to rare flakiness (private key occasionally not attached after |
| | | 43 | | /// import). To make behavior deterministic we now disable appending by default and allow it to |
| | | 44 | | /// be re-enabled explicitly via the environment variable KESTRUN_APPEND_KEY_TO_PEM. |
| | | 45 | | /// Set KESTRUN_APPEND_KEY_TO_PEM=1 (or "true") to re-enable. |
| | | 46 | | /// </summary> |
| | | 47 | | private static bool ShouldAppendKeyToPem => |
| | 2 | 48 | | string.Equals(Environment.GetEnvironmentVariable("KESTRUN_APPEND_KEY_TO_PEM"), "1", StringComparison.OrdinalIgno |
| | 2 | 49 | | string.Equals(Environment.GetEnvironmentVariable("KESTRUN_APPEND_KEY_TO_PEM"), "true", StringComparison.OrdinalI |
| | | 50 | | |
| | | 51 | | #region Self-signed certificate |
| | | 52 | | /// <summary> |
| | | 53 | | /// Creates a new self-signed X509 certificate using the specified options. |
| | | 54 | | /// </summary> |
| | | 55 | | /// <param name="o">Options for creating the self-signed certificate.</param> |
| | | 56 | | /// <returns>A new self-signed X509Certificate2 instance.</returns> |
| | | 57 | | public static X509Certificate2 NewSelfSigned(SelfSignedOptions o) |
| | | 58 | | { |
| | 12 | 59 | | var random = new SecureRandom(new CryptoApiRandomGenerator()); |
| | | 60 | | |
| | | 61 | | // ── 1. Key pair ─────────────────────────────────────────────────────────── |
| | 12 | 62 | | var keyPair = |
| | 12 | 63 | | o.KeyType switch |
| | 12 | 64 | | { |
| | 12 | 65 | | KeyType.Rsa => GenRsaKeyPair(o.KeyLength, random), |
| | 0 | 66 | | KeyType.Ecdsa => GenEcKeyPair(o.KeyLength, random), |
| | 0 | 67 | | _ => throw new ArgumentOutOfRangeException() |
| | 12 | 68 | | }; |
| | | 69 | | |
| | | 70 | | // ── 2. Certificate body ─────────────────────────────────────────────────── |
| | 12 | 71 | | var notBefore = DateTime.UtcNow.AddMinutes(-5); |
| | 12 | 72 | | var notAfter = notBefore.AddDays(o.ValidDays); |
| | 12 | 73 | | var serial = BigIntegers.CreateRandomInRange( |
| | 12 | 74 | | BigInteger.One, BigInteger.ValueOf(long.MaxValue), random); |
| | | 75 | | |
| | 12 | 76 | | var subjectDn = new X509Name($"CN={o.DnsNames.First()}"); |
| | 12 | 77 | | var gen = new X509V3CertificateGenerator(); |
| | 12 | 78 | | gen.SetSerialNumber(serial); |
| | 12 | 79 | | gen.SetIssuerDN(subjectDn); |
| | 12 | 80 | | gen.SetSubjectDN(subjectDn); |
| | 12 | 81 | | gen.SetNotBefore(notBefore); |
| | 12 | 82 | | gen.SetNotAfter(notAfter); |
| | 12 | 83 | | gen.SetPublicKey(keyPair.Public); |
| | | 84 | | |
| | | 85 | | // SANs |
| | 12 | 86 | | var altNames = o.DnsNames |
| | 23 | 87 | | .Select(n => new GeneralName( |
| | 23 | 88 | | IPAddress.TryParse(n, out _) ? |
| | 23 | 89 | | GeneralName.IPAddress : GeneralName.DnsName, n)) |
| | 12 | 90 | | .ToArray(); |
| | 12 | 91 | | gen.AddExtension(X509Extensions.SubjectAlternativeName, false, |
| | 12 | 92 | | new DerSequence(altNames)); |
| | | 93 | | |
| | | 94 | | // EKU |
| | 12 | 95 | | var eku = o.Purposes ?? |
| | 12 | 96 | | [ |
| | 12 | 97 | | KeyPurposeID.id_kp_serverAuth, |
| | 12 | 98 | | KeyPurposeID.id_kp_clientAuth |
| | 12 | 99 | | ]; |
| | 12 | 100 | | gen.AddExtension(X509Extensions.ExtendedKeyUsage, false, |
| | 12 | 101 | | new ExtendedKeyUsage([.. eku])); |
| | | 102 | | |
| | | 103 | | // KeyUsage – allow digitalSignature & keyEncipherment |
| | 12 | 104 | | gen.AddExtension(X509Extensions.KeyUsage, true, |
| | 12 | 105 | | new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment)); |
| | | 106 | | |
| | | 107 | | // ── 3. Sign & output ────────────────────────────────────────────────────── |
| | 12 | 108 | | var sigAlg = o.KeyType == KeyType.Rsa ? "SHA256WITHRSA" : "SHA384WITHECDSA"; |
| | 12 | 109 | | var signer = new Asn1SignatureFactory(sigAlg, keyPair.Private, random); |
| | 12 | 110 | | var cert = gen.Generate(signer); |
| | | 111 | | |
| | 12 | 112 | | return ToX509Cert2(cert, keyPair.Private, |
| | 12 | 113 | | o.Exportable ? X509KeyStorageFlags.Exportable : X509KeyStorageFlags.DefaultKeySet, |
| | 12 | 114 | | o.Ephemeral); |
| | | 115 | | } |
| | | 116 | | #endregion |
| | | 117 | | |
| | | 118 | | #region CSR |
| | | 119 | | |
| | | 120 | | /// <summary> |
| | | 121 | | /// Creates a new Certificate Signing Request (CSR) and returns the PEM-encoded CSR and the private key. |
| | | 122 | | /// </summary> |
| | | 123 | | /// <param name="options">The options for the CSR.</param> |
| | | 124 | | /// <param name="encryptionPassword">The password to encrypt the private key, if desired.</param> |
| | | 125 | | /// <returns>A <see cref="CsrResult"/> containing the CSR and private key information.</returns> |
| | | 126 | | /// <exception cref="ArgumentOutOfRangeException"></exception> |
| | | 127 | | public static CsrResult NewCertificateRequest(CsrOptions options, ReadOnlySpan<char> encryptionPassword = default) |
| | | 128 | | { |
| | | 129 | | // 0️⃣ Keypair |
| | 2 | 130 | | var random = new SecureRandom(new CryptoApiRandomGenerator()); |
| | 2 | 131 | | var keyPair = options.KeyType switch |
| | 2 | 132 | | { |
| | 1 | 133 | | KeyType.Rsa => GenRsaKeyPair(options.KeyLength, random), |
| | 1 | 134 | | KeyType.Ecdsa => GenEcKeyPair(options.KeyLength, random), |
| | 0 | 135 | | _ => throw new ArgumentOutOfRangeException(nameof(options.KeyType)) |
| | 2 | 136 | | }; |
| | | 137 | | |
| | | 138 | | // 1️⃣ Subject DN |
| | 2 | 139 | | var order = new List<DerObjectIdentifier>(); |
| | 2 | 140 | | var attrs = new Dictionary<DerObjectIdentifier, string>(); |
| | | 141 | | void Add(DerObjectIdentifier oid, string? v) |
| | | 142 | | { |
| | 12 | 143 | | if (!string.IsNullOrWhiteSpace(v)) { order.Add(oid); attrs[oid] = v; } |
| | 8 | 144 | | } |
| | 2 | 145 | | Add(X509Name.C, options.Country); |
| | 2 | 146 | | Add(X509Name.O, options.Org); |
| | 2 | 147 | | Add(X509Name.OU, options.OrgUnit); |
| | 2 | 148 | | Add(X509Name.CN, options.CommonName ?? options.DnsNames.First()); |
| | 2 | 149 | | var subject = new X509Name(order, attrs); |
| | | 150 | | |
| | | 151 | | // 2️⃣ SAN extension |
| | 2 | 152 | | var altNames = options.DnsNames |
| | 3 | 153 | | .Select(d => new GeneralName( |
| | 3 | 154 | | IPAddress.TryParse(d, out _) |
| | 3 | 155 | | ? GeneralName.IPAddress |
| | 3 | 156 | | : GeneralName.DnsName, d)) |
| | 2 | 157 | | .ToArray(); |
| | 2 | 158 | | var sanSeq = new DerSequence(altNames); |
| | | 159 | | |
| | 2 | 160 | | var extGen = new X509ExtensionsGenerator(); |
| | 2 | 161 | | extGen.AddExtension(X509Extensions.SubjectAlternativeName, false, sanSeq); |
| | 2 | 162 | | var extensions = extGen.Generate(); |
| | | 163 | | |
| | 2 | 164 | | var extensionRequestAttr = new AttributePkcs( |
| | 2 | 165 | | PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, |
| | 2 | 166 | | new DerSet(extensions)); |
| | 2 | 167 | | var attrSet = new DerSet(extensionRequestAttr); |
| | | 168 | | |
| | | 169 | | // 3️⃣ CSR |
| | 2 | 170 | | var sigAlg = options.KeyType == KeyType.Rsa ? "SHA256WITHRSA" : "SHA384WITHECDSA"; |
| | 2 | 171 | | var csr = new Pkcs10CertificationRequest(sigAlg, subject, keyPair.Public, attrSet, keyPair.Private); |
| | | 172 | | |
| | | 173 | | // 4️⃣ CSR PEM + DER |
| | | 174 | | string csrPem; |
| | 2 | 175 | | using (var sw = new StringWriter()) |
| | | 176 | | { |
| | 2 | 177 | | new PemWriter(sw).WriteObject(csr); |
| | 2 | 178 | | csrPem = sw.ToString(); |
| | 2 | 179 | | } |
| | 2 | 180 | | var csrDer = csr.GetEncoded(); |
| | | 181 | | |
| | | 182 | | // 5️⃣ Private key PEM + DER |
| | | 183 | | string privateKeyPem; |
| | 2 | 184 | | using (var sw = new StringWriter()) |
| | | 185 | | { |
| | 2 | 186 | | new PemWriter(sw).WriteObject(keyPair.Private); |
| | 2 | 187 | | privateKeyPem = sw.ToString(); |
| | 2 | 188 | | } |
| | 2 | 189 | | var pkInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private); |
| | 2 | 190 | | var privateKeyDer = pkInfo.GetEncoded(); |
| | | 191 | | |
| | | 192 | | // 6️⃣ Optional encrypted PEM |
| | 2 | 193 | | string? privateKeyPemEncrypted = null; |
| | 2 | 194 | | if (!encryptionPassword.IsEmpty) |
| | | 195 | | { |
| | 0 | 196 | | var pwd = encryptionPassword.ToArray(); // BC requires char[] |
| | | 197 | | try |
| | | 198 | | { |
| | 0 | 199 | | var gen = new Pkcs8Generator(keyPair.Private, Pkcs8Generator.PbeSha1_3DES) |
| | 0 | 200 | | { |
| | 0 | 201 | | Password = pwd |
| | 0 | 202 | | }; |
| | 0 | 203 | | using var encSw = new StringWriter(); |
| | 0 | 204 | | new PemWriter(encSw).WriteObject(gen); |
| | 0 | 205 | | privateKeyPemEncrypted = encSw.ToString(); |
| | | 206 | | } |
| | | 207 | | finally |
| | | 208 | | { |
| | 0 | 209 | | Array.Clear(pwd, 0, pwd.Length); // wipe memory |
| | 0 | 210 | | } |
| | | 211 | | } |
| | | 212 | | |
| | | 213 | | // 7️⃣ Public key PEM + DER |
| | 2 | 214 | | var spki = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public); |
| | 2 | 215 | | var publicKeyDer = spki.GetEncoded(); |
| | | 216 | | string publicKeyPem; |
| | 2 | 217 | | using (var sw = new StringWriter()) |
| | | 218 | | { |
| | 2 | 219 | | new PemWriter(sw).WriteObject(spki); |
| | 2 | 220 | | publicKeyPem = sw.ToString(); |
| | 2 | 221 | | } |
| | | 222 | | |
| | 2 | 223 | | return new CsrResult( |
| | 2 | 224 | | csrPem, |
| | 2 | 225 | | csrDer, |
| | 2 | 226 | | keyPair.Private, |
| | 2 | 227 | | privateKeyPem, |
| | 2 | 228 | | privateKeyDer, |
| | 2 | 229 | | privateKeyPemEncrypted, |
| | 2 | 230 | | publicKeyPem, |
| | 2 | 231 | | publicKeyDer |
| | 2 | 232 | | ); |
| | | 233 | | } |
| | | 234 | | |
| | | 235 | | #endregion |
| | | 236 | | |
| | | 237 | | #region Import |
| | | 238 | | /// <summary> |
| | | 239 | | /// Imports an X509 certificate from the specified file path, with optional password and private key file. |
| | | 240 | | /// </summary> |
| | | 241 | | /// <param name="certPath">The path to the certificate file.</param> |
| | | 242 | | /// <param name="password">The password for the certificate, if required.</param> |
| | | 243 | | /// <param name="privateKeyPath">The path to the private key file, if separate.</param> |
| | | 244 | | /// <param name="flags">Key storage flags for the imported certificate.</param> |
| | | 245 | | /// <returns>The imported X509Certificate2 instance.</returns> |
| | | 246 | | public static X509Certificate2 Import( |
| | | 247 | | string certPath, |
| | | 248 | | ReadOnlySpan<char> password = default, |
| | | 249 | | string? privateKeyPath = null, |
| | | 250 | | X509KeyStorageFlags flags = X509KeyStorageFlags.DefaultKeySet | X509KeyStorageFlags.Exportable) |
| | | 251 | | { |
| | 9 | 252 | | ValidateImportInputs(certPath, privateKeyPath); |
| | | 253 | | |
| | 6 | 254 | | var ext = Path.GetExtension(certPath).ToLowerInvariant(); |
| | 6 | 255 | | return ext switch |
| | 6 | 256 | | { |
| | 2 | 257 | | ".pfx" or ".p12" => ImportPfx(certPath, password, flags), |
| | 1 | 258 | | ".cer" or ".der" => ImportDer(certPath), |
| | 3 | 259 | | ".pem" or ".crt" => ImportPem(certPath, password, privateKeyPath), |
| | 0 | 260 | | _ => throw new NotSupportedException($"Certificate extension '{ext}' is not supported.") |
| | 6 | 261 | | }; |
| | | 262 | | } |
| | | 263 | | |
| | | 264 | | /// <summary> |
| | | 265 | | /// Validates the inputs for importing a certificate. |
| | | 266 | | /// </summary> |
| | | 267 | | /// <param name="certPath">The path to the certificate file.</param> |
| | | 268 | | /// <param name="privateKeyPath">The path to the private key file, if separate.</param> |
| | | 269 | | private static void ValidateImportInputs(string certPath, string? privateKeyPath) |
| | | 270 | | { |
| | 9 | 271 | | if (string.IsNullOrEmpty(certPath)) |
| | | 272 | | { |
| | 1 | 273 | | throw new ArgumentException("Certificate path cannot be null or empty.", nameof(certPath)); |
| | | 274 | | } |
| | 8 | 275 | | if (!File.Exists(certPath)) |
| | | 276 | | { |
| | 1 | 277 | | throw new FileNotFoundException("Certificate file not found.", certPath); |
| | | 278 | | } |
| | 7 | 279 | | if (!string.IsNullOrEmpty(privateKeyPath) && !File.Exists(privateKeyPath)) |
| | | 280 | | { |
| | 1 | 281 | | throw new FileNotFoundException("Private key file not found.", privateKeyPath); |
| | | 282 | | } |
| | 6 | 283 | | } |
| | | 284 | | |
| | | 285 | | /// <summary> |
| | | 286 | | /// Imports a PFX certificate from the specified file path. |
| | | 287 | | /// </summary> |
| | | 288 | | /// <param name="certPath">The path to the certificate file.</param> |
| | | 289 | | /// <param name="password">The password for the certificate, if required.</param> |
| | | 290 | | /// <param name="flags">Key storage flags for the imported certificate.</param> |
| | | 291 | | /// <returns>The imported X509Certificate2 instance.</returns> |
| | | 292 | | private static X509Certificate2 ImportPfx(string certPath, ReadOnlySpan<char> password, X509KeyStorageFlags flags) |
| | | 293 | | #if NET9_0_OR_GREATER |
| | | 294 | | => X509CertificateLoader.LoadPkcs12FromFile(certPath, password, flags, Pkcs12LoaderLimits.Defaults); |
| | | 295 | | #else |
| | 2 | 296 | | => new(File.ReadAllBytes(certPath), password, flags); |
| | | 297 | | #endif |
| | | 298 | | |
| | | 299 | | private static X509Certificate2 ImportDer(string certPath) |
| | | 300 | | #if NET9_0_OR_GREATER |
| | | 301 | | => X509CertificateLoader.LoadCertificateFromFile(certPath); |
| | | 302 | | #else |
| | 1 | 303 | | => new(File.ReadAllBytes(certPath)); |
| | | 304 | | #endif |
| | | 305 | | |
| | | 306 | | /// <summary> |
| | | 307 | | /// Imports a PEM certificate from the specified file path. |
| | | 308 | | /// </summary> |
| | | 309 | | /// <param name="certPath">The path to the certificate file.</param> |
| | | 310 | | /// <param name="password">The password for the certificate, if required.</param> |
| | | 311 | | /// <param name="privateKeyPath">The path to the private key file, if separate.</param> |
| | | 312 | | /// <returns>The imported X509Certificate2 instance.</returns> |
| | | 313 | | private static X509Certificate2 ImportPem(string certPath, ReadOnlySpan<char> password, string? privateKeyPath) |
| | | 314 | | { |
| | | 315 | | // No separate key file provided |
| | 3 | 316 | | if (string.IsNullOrEmpty(privateKeyPath)) |
| | | 317 | | { |
| | 1 | 318 | | return password.IsEmpty |
| | 1 | 319 | | ? LoadCertOnlyPem(certPath) |
| | 1 | 320 | | : X509Certificate2.CreateFromEncryptedPemFile(certPath, password); |
| | | 321 | | } |
| | | 322 | | |
| | | 323 | | // Separate key file provided |
| | 2 | 324 | | return password.IsEmpty |
| | 2 | 325 | | ? ImportPemUnencrypted(certPath, privateKeyPath) |
| | 2 | 326 | | : ImportPemEncrypted(certPath, password, privateKeyPath); |
| | | 327 | | } |
| | | 328 | | |
| | | 329 | | /// <summary> |
| | | 330 | | /// Imports an unencrypted PEM certificate from the specified file path. |
| | | 331 | | /// </summary> |
| | | 332 | | /// <param name="certPath">The path to the certificate file.</param> |
| | | 333 | | /// <param name="privateKeyPath">The path to the private key file.</param> |
| | | 334 | | /// <returns>The imported X509Certificate2 instance.</returns> |
| | | 335 | | private static X509Certificate2 ImportPemUnencrypted(string certPath, string privateKeyPath) |
| | 1 | 336 | | => X509Certificate2.CreateFromPemFile(certPath, privateKeyPath); |
| | | 337 | | |
| | | 338 | | /// <summary> |
| | | 339 | | /// Imports a PEM certificate from the specified file path. |
| | | 340 | | /// </summary> |
| | | 341 | | /// <param name="certPath">The path to the certificate file.</param> |
| | | 342 | | /// <param name="password">The password for the certificate, if required.</param> |
| | | 343 | | /// <param name="privateKeyPath">The path to the private key file, if separate.</param> |
| | | 344 | | /// <returns>The imported X509Certificate2 instance.</returns> |
| | | 345 | | private static X509Certificate2 ImportPemEncrypted(string certPath, ReadOnlySpan<char> password, string privateKeyPa |
| | | 346 | | { |
| | | 347 | | // Prefer single-file path (combined) first for reliability on some platforms |
| | | 348 | | try |
| | | 349 | | { |
| | 1 | 350 | | var single = X509Certificate2.CreateFromEncryptedPemFile(certPath, password); |
| | 0 | 351 | | if (single.HasPrivateKey) |
| | | 352 | | { |
| | 0 | 353 | | Log.Debug("Imported encrypted PEM using single-file path (combined cert+key) for {CertPath}", certPath); |
| | 0 | 354 | | return single; |
| | | 355 | | } |
| | 0 | 356 | | } |
| | 1 | 357 | | catch (Exception exSingle) |
| | | 358 | | { |
| | 1 | 359 | | Log.Debug(exSingle, "Single-file encrypted PEM import failed, falling back to separate key file {KeyFile}", |
| | 1 | 360 | | } |
| | | 361 | | |
| | 1 | 362 | | var loaded = X509Certificate2.CreateFromEncryptedPemFile(certPath, password, privateKeyPath); |
| | | 363 | | |
| | 1 | 364 | | if (loaded.HasPrivateKey) |
| | | 365 | | { |
| | 1 | 366 | | return loaded; |
| | | 367 | | } |
| | | 368 | | |
| | | 369 | | // Fallback manual pairing if platform failed to associate the key |
| | 0 | 370 | | TryManualEncryptedPemPairing(certPath, password, privateKeyPath, ref loaded); |
| | 0 | 371 | | return loaded; |
| | 0 | 372 | | } |
| | | 373 | | |
| | | 374 | | /// <summary> |
| | | 375 | | /// Tries to manually pair an encrypted PEM certificate with its private key. |
| | | 376 | | /// </summary> |
| | | 377 | | /// <param name="certPath">The path to the certificate file.</param> |
| | | 378 | | /// <param name="password">The password for the certificate, if required.</param> |
| | | 379 | | /// <param name="privateKeyPath">The path to the private key file, if separate.</param> |
| | | 380 | | /// <param name="loaded">The loaded X509Certificate2 instance.</param> |
| | | 381 | | private static void TryManualEncryptedPemPairing(string certPath, ReadOnlySpan<char> password, string privateKeyPath |
| | | 382 | | { |
| | | 383 | | try |
| | | 384 | | { |
| | 0 | 385 | | var certOnly = LoadCertOnlyPem(certPath); |
| | 0 | 386 | | var encDer = ExtractEncryptedPemDer(privateKeyPath); |
| | | 387 | | |
| | 0 | 388 | | if (encDer is null) |
| | | 389 | | { |
| | 0 | 390 | | Log.Debug("Encrypted PEM manual pairing fallback skipped: markers not found in key file {KeyFile}", priv |
| | 0 | 391 | | return; |
| | | 392 | | } |
| | | 393 | | |
| | 0 | 394 | | var lastErr = TryPairCertificateWithKey(certOnly, password, encDer, ref loaded); |
| | | 395 | | |
| | 0 | 396 | | if (lastErr != null) |
| | | 397 | | { |
| | 0 | 398 | | Log.Debug(lastErr, "Encrypted PEM manual pairing attempts failed (all rounds); returning original loaded |
| | | 399 | | } |
| | 0 | 400 | | } |
| | 0 | 401 | | catch (Exception ex) |
| | | 402 | | { |
| | 0 | 403 | | Log.Debug(ex, "Encrypted PEM manual pairing fallback failed unexpectedly; returning original loaded certific |
| | 0 | 404 | | } |
| | 0 | 405 | | } |
| | | 406 | | |
| | | 407 | | /// <summary> |
| | | 408 | | /// Extracts the encrypted PEM DER bytes from a private key file. |
| | | 409 | | /// </summary> |
| | | 410 | | /// <param name="privateKeyPath">The path to the private key file.</param> |
| | | 411 | | /// <returns>The DER bytes if successful, null otherwise.</returns> |
| | | 412 | | private static byte[]? ExtractEncryptedPemDer(string privateKeyPath) |
| | | 413 | | { |
| | | 414 | | const string encBegin = "-----BEGIN ENCRYPTED PRIVATE KEY-----"; |
| | | 415 | | const string encEnd = "-----END ENCRYPTED PRIVATE KEY-----"; |
| | | 416 | | |
| | 0 | 417 | | byte[]? encDer = null; |
| | 0 | 418 | | for (var attempt = 0; attempt < 5 && encDer is null; attempt++) |
| | | 419 | | { |
| | 0 | 420 | | var keyPem = File.ReadAllText(privateKeyPath); |
| | 0 | 421 | | var start = keyPem.IndexOf(encBegin, StringComparison.Ordinal); |
| | 0 | 422 | | var end = keyPem.IndexOf(encEnd, StringComparison.Ordinal); |
| | 0 | 423 | | if (start >= 0 && end > start) |
| | | 424 | | { |
| | 0 | 425 | | start += encBegin.Length; |
| | 0 | 426 | | var b64 = keyPem[start..end].Replace("\r", "").Replace("\n", "").Trim(); |
| | 0 | 427 | | try { encDer = Convert.FromBase64String(b64); } |
| | 0 | 428 | | catch (FormatException fe) |
| | | 429 | | { |
| | 0 | 430 | | Log.Debug(fe, "Base64 decode failed on attempt {Attempt} reading encrypted key; retrying", attempt + |
| | 0 | 431 | | } |
| | | 432 | | } |
| | 0 | 433 | | if (encDer is null) |
| | | 434 | | { |
| | 0 | 435 | | Thread.Sleep(40 * (attempt + 1)); |
| | | 436 | | } |
| | | 437 | | } |
| | | 438 | | |
| | 0 | 439 | | return encDer; |
| | | 440 | | } |
| | | 441 | | |
| | | 442 | | /// <summary> |
| | | 443 | | /// Attempts to pair a certificate with an encrypted private key using RSA and ECDSA. |
| | | 444 | | /// </summary> |
| | | 445 | | /// <param name="certOnly">The certificate without a private key.</param> |
| | | 446 | | /// <param name="password">The password for the encrypted key.</param> |
| | | 447 | | /// <param name="encDer">The encrypted DER bytes.</param> |
| | | 448 | | /// <param name="loaded">The loaded certificate (updated if pairing succeeds).</param> |
| | | 449 | | /// <returns>The last exception encountered, or null if pairing succeeded.</returns> |
| | | 450 | | private static Exception? TryPairCertificateWithKey(X509Certificate2 certOnly, ReadOnlySpan<char> password, byte[] e |
| | | 451 | | { |
| | 0 | 452 | | Exception? lastErr = null; |
| | 0 | 453 | | for (var round = 0; round < 2; round++) |
| | | 454 | | { |
| | 0 | 455 | | if (TryPairWithRsa(certOnly, password, encDer, round, ref loaded, ref lastErr)) |
| | | 456 | | { |
| | 0 | 457 | | return null; |
| | | 458 | | } |
| | | 459 | | |
| | 0 | 460 | | if (TryPairWithEcdsa(certOnly, password, encDer, round, ref loaded, ref lastErr)) |
| | | 461 | | { |
| | 0 | 462 | | return null; |
| | | 463 | | } |
| | | 464 | | |
| | 0 | 465 | | Thread.Sleep(25 * (round + 1)); |
| | | 466 | | } |
| | 0 | 467 | | return lastErr; |
| | | 468 | | } |
| | | 469 | | |
| | | 470 | | /// <summary> |
| | | 471 | | /// Tries to pair a certificate with an RSA private key. |
| | | 472 | | /// </summary> |
| | | 473 | | /// <param name="certOnly">The certificate without a private key.</param> |
| | | 474 | | /// <param name="password">The password for the encrypted key.</param> |
| | | 475 | | /// <param name="encDer">The encrypted DER bytes.</param> |
| | | 476 | | /// <param name="round">The attempt round number.</param> |
| | | 477 | | /// <param name="loaded">The loaded certificate (updated if pairing succeeds).</param> |
| | | 478 | | /// <param name="lastErr">The last exception encountered (updated on failure).</param> |
| | | 479 | | /// <returns>True if pairing succeeded, false otherwise.</returns> |
| | | 480 | | private static bool TryPairWithRsa(X509Certificate2 certOnly, ReadOnlySpan<char> password, byte[] encDer, int round, |
| | | 481 | | { |
| | | 482 | | try |
| | | 483 | | { |
| | 0 | 484 | | using var rsa = RSA.Create(); |
| | 0 | 485 | | rsa.ImportEncryptedPkcs8PrivateKey(password, encDer, out _); |
| | 0 | 486 | | var withKey = certOnly.CopyWithPrivateKey(rsa); |
| | 0 | 487 | | if (withKey.HasPrivateKey) |
| | | 488 | | { |
| | 0 | 489 | | Log.Debug("Encrypted PEM manual pairing succeeded with RSA private key (round {Round}).", round + 1); |
| | 0 | 490 | | loaded = withKey; |
| | 0 | 491 | | return true; |
| | | 492 | | } |
| | 0 | 493 | | } |
| | 0 | 494 | | catch (Exception exRsa) |
| | | 495 | | { |
| | 0 | 496 | | lastErr = lastErr is null ? exRsa : new AggregateException(lastErr, exRsa); |
| | 0 | 497 | | } |
| | 0 | 498 | | return false; |
| | 0 | 499 | | } |
| | | 500 | | |
| | | 501 | | /// <summary> |
| | | 502 | | /// Tries to pair a certificate with an ECDSA private key. |
| | | 503 | | /// </summary> |
| | | 504 | | /// <param name="certOnly">The certificate without a private key.</param> |
| | | 505 | | /// <param name="password">The password for the encrypted key.</param> |
| | | 506 | | /// <param name="encDer">The encrypted DER bytes.</param> |
| | | 507 | | /// <param name="round">The attempt round number.</param> |
| | | 508 | | /// <param name="loaded">The loaded certificate (updated if pairing succeeds).</param> |
| | | 509 | | /// <param name="lastErr">The last exception encountered (updated on failure).</param> |
| | | 510 | | /// <returns>True if pairing succeeded, false otherwise.</returns> |
| | | 511 | | private static bool TryPairWithEcdsa(X509Certificate2 certOnly, ReadOnlySpan<char> password, byte[] encDer, int roun |
| | | 512 | | { |
| | | 513 | | try |
| | | 514 | | { |
| | 0 | 515 | | using var ecdsa = ECDsa.Create(); |
| | 0 | 516 | | ecdsa.ImportEncryptedPkcs8PrivateKey(password, encDer, out _); |
| | 0 | 517 | | var withKey = certOnly.CopyWithPrivateKey(ecdsa); |
| | 0 | 518 | | if (withKey.HasPrivateKey) |
| | | 519 | | { |
| | 0 | 520 | | Log.Debug("Encrypted PEM manual pairing succeeded with ECDSA private key (round {Round}).", round + 1); |
| | 0 | 521 | | loaded = withKey; |
| | 0 | 522 | | return true; |
| | | 523 | | } |
| | 0 | 524 | | } |
| | 0 | 525 | | catch (Exception exEc) |
| | | 526 | | { |
| | 0 | 527 | | lastErr = lastErr is null ? exEc : new AggregateException(lastErr, exEc); |
| | 0 | 528 | | } |
| | 0 | 529 | | return false; |
| | 0 | 530 | | } |
| | | 531 | | |
| | | 532 | | /// <summary> |
| | | 533 | | /// Loads a certificate from a PEM file that contains *only* a CERTIFICATE block (no key). |
| | | 534 | | /// </summary> |
| | | 535 | | /// <param name="certPath">The path to the certificate file.</param> |
| | | 536 | | /// <returns>The loaded X509Certificate2 instance.</returns> |
| | | 537 | | private static X509Certificate2 LoadCertOnlyPem(string certPath) |
| | | 538 | | { |
| | | 539 | | // 1) Read + trim the whole PEM text |
| | 1 | 540 | | var pem = File.ReadAllText(certPath).Trim(); |
| | | 541 | | |
| | | 542 | | // 2) Define the BEGIN/END markers |
| | | 543 | | const string begin = "-----BEGIN CERTIFICATE-----"; |
| | | 544 | | const string end = "-----END CERTIFICATE-----"; |
| | | 545 | | |
| | | 546 | | // 3) Find their positions |
| | 1 | 547 | | var start = pem.IndexOf(begin, StringComparison.Ordinal); |
| | 1 | 548 | | if (start < 0) |
| | | 549 | | { |
| | 0 | 550 | | throw new InvalidDataException("BEGIN CERTIFICATE marker not found"); |
| | | 551 | | } |
| | | 552 | | |
| | 1 | 553 | | start += begin.Length; |
| | | 554 | | |
| | 1 | 555 | | var stop = pem.IndexOf(end, start, StringComparison.Ordinal); |
| | 1 | 556 | | if (stop < 0) |
| | | 557 | | { |
| | 0 | 558 | | throw new InvalidDataException("END CERTIFICATE marker not found"); |
| | | 559 | | } |
| | | 560 | | |
| | | 561 | | // 4) Extract, clean, and decode the Base64 payload |
| | 1 | 562 | | var b64 = pem[start..stop] |
| | 1 | 563 | | .Replace("\r", "") |
| | 1 | 564 | | .Replace("\n", "") |
| | 1 | 565 | | .Trim(); |
| | 1 | 566 | | var der = Convert.FromBase64String(b64); |
| | | 567 | | |
| | | 568 | | // 5) Return the X509Certificate2 |
| | | 569 | | |
| | | 570 | | #if NET9_0_OR_GREATER |
| | | 571 | | return X509CertificateLoader.LoadCertificate(der); |
| | | 572 | | #else |
| | | 573 | | // .NET 8 or earlier path, using X509Certificate2 ctor |
| | | 574 | | // Note: this will not work in .NET 9+ due to the new X509CertificateLoader API |
| | | 575 | | // which requires a byte array or a file path. |
| | 1 | 576 | | return new X509Certificate2(der); |
| | | 577 | | #endif |
| | | 578 | | } |
| | | 579 | | |
| | | 580 | | /// <summary> |
| | | 581 | | /// Imports an X509 certificate from the specified file path, using a SecureString password and optional private key |
| | | 582 | | /// </summary> |
| | | 583 | | /// <param name="certPath">The path to the certificate file.</param> |
| | | 584 | | /// <param name="password">The SecureString password for the certificate, if required.</param> |
| | | 585 | | /// <param name="privateKeyPath">The path to the private key file, if separate.</param> |
| | | 586 | | /// <param name="flags">Key storage flags for the imported certificate.</param> |
| | | 587 | | /// <returns>The imported X509Certificate2 instance.</returns> |
| | | 588 | | public static X509Certificate2 Import( |
| | | 589 | | string certPath, |
| | | 590 | | SecureString password, |
| | | 591 | | string? privateKeyPath = null, |
| | | 592 | | X509KeyStorageFlags flags = X509KeyStorageFlags.DefaultKeySet | X509KeyStorageFlags.Exportable) |
| | | 593 | | { |
| | 1 | 594 | | X509Certificate2? result = null; |
| | 1 | 595 | | Log.Debug("Importing certificate from {CertPath} with flags {Flags}", certPath, flags); |
| | | 596 | | // ToSecureSpan zero-frees its buffer as soon as this callback returns. |
| | 1 | 597 | | password.ToSecureSpan(span => |
| | 1 | 598 | | { |
| | 1 | 599 | | // capture the return value of the span-based overload |
| | 1 | 600 | | result = Import(certPath: certPath, password: span, privateKeyPath: privateKeyPath, flags: flags); |
| | 2 | 601 | | }); |
| | | 602 | | |
| | | 603 | | // at this point, unmanaged memory is already zeroed |
| | 1 | 604 | | return result!; // non-null because the callback always runs exactly once |
| | | 605 | | } |
| | | 606 | | |
| | | 607 | | /// <summary> |
| | | 608 | | /// Imports an X509 certificate from the specified file path, with optional private key file and key storage flags. |
| | | 609 | | /// </summary> |
| | | 610 | | /// <param name="certPath">The path to the certificate file.</param> |
| | | 611 | | /// <param name="privateKeyPath">The path to the private key file, if separate.</param> |
| | | 612 | | /// <param name="flags">Key storage flags for the imported certificate.</param> |
| | | 613 | | /// <returns>The imported X509Certificate2 instance.</returns> |
| | | 614 | | public static X509Certificate2 Import( |
| | | 615 | | string certPath, |
| | | 616 | | string? privateKeyPath = null, |
| | | 617 | | X509KeyStorageFlags flags = X509KeyStorageFlags.DefaultKeySet | X509KeyStorageFlags.Exportable) |
| | | 618 | | { |
| | | 619 | | // ToSecureSpan zero-frees its buffer as soon as this callback returns. |
| | 2 | 620 | | ReadOnlySpan<char> passwordSpan = default; |
| | | 621 | | // capture the return value of the span-based overload |
| | 2 | 622 | | var result = Import(certPath: certPath, password: passwordSpan, privateKeyPath: privateKeyPath, flags: flags); |
| | 1 | 623 | | return result; |
| | | 624 | | } |
| | | 625 | | |
| | | 626 | | /// <summary> |
| | | 627 | | /// Imports an X509 certificate from the specified file path. |
| | | 628 | | /// </summary> |
| | | 629 | | /// <param name="certPath">The path to the certificate file.</param> |
| | | 630 | | /// <returns>The imported X509Certificate2 instance.</returns> |
| | | 631 | | public static X509Certificate2 Import(string certPath) |
| | | 632 | | { |
| | | 633 | | // ToSecureSpan zero-frees its buffer as soon as this callback returns. |
| | 4 | 634 | | ReadOnlySpan<char> passwordSpan = default; |
| | | 635 | | // capture the return value of the span-based overload |
| | 4 | 636 | | var result = Import(certPath: certPath, password: passwordSpan); |
| | 2 | 637 | | return result; |
| | | 638 | | } |
| | | 639 | | |
| | | 640 | | #endregion |
| | | 641 | | |
| | | 642 | | #region Export |
| | | 643 | | /// <summary> |
| | | 644 | | /// Exports the specified X509 certificate to a file in the given format, with optional password and private key inc |
| | | 645 | | /// </summary> |
| | | 646 | | /// <param name="cert">The X509Certificate2 to export.</param> |
| | | 647 | | /// <param name="filePath">The file path to export the certificate to.</param> |
| | | 648 | | /// <param name="fmt">The export format (Pfx or Pem).</param> |
| | | 649 | | /// <param name="password">The password to protect the exported certificate or private key, if applicable.</param> |
| | | 650 | | /// <param name="includePrivateKey">Whether to include the private key in the export.</param> |
| | | 651 | | public static void Export(X509Certificate2 cert, string filePath, ExportFormat fmt, |
| | | 652 | | ReadOnlySpan<char> password = default, bool includePrivateKey = false) |
| | | 653 | | { |
| | | 654 | | // Normalize/validate target path and format |
| | 4 | 655 | | filePath = NormalizeExportPath(filePath, fmt); |
| | | 656 | | |
| | | 657 | | // Ensure output directory exists |
| | 4 | 658 | | EnsureOutputDirectoryExists(filePath); |
| | | 659 | | |
| | | 660 | | // Prepare password shapes once |
| | 4 | 661 | | using var shapes = CreatePasswordShapes(password); |
| | | 662 | | |
| | | 663 | | switch (fmt) |
| | | 664 | | { |
| | | 665 | | case ExportFormat.Pfx: |
| | 2 | 666 | | ExportPfx(cert, filePath, shapes.Secure); |
| | 2 | 667 | | break; |
| | | 668 | | case ExportFormat.Pem: |
| | 2 | 669 | | ExportPem(cert, filePath, password, includePrivateKey); |
| | 2 | 670 | | break; |
| | | 671 | | default: |
| | 0 | 672 | | throw new NotSupportedException($"Unsupported export format: {fmt}"); |
| | | 673 | | } |
| | 4 | 674 | | } |
| | | 675 | | |
| | | 676 | | /// <summary> |
| | | 677 | | /// Normalizes the export file path based on the desired export format. |
| | | 678 | | /// </summary> |
| | | 679 | | /// <param name="filePath">The original file path.</param> |
| | | 680 | | /// <param name="fmt">The desired export format.</param> |
| | | 681 | | /// <returns>The normalized file path.</returns> |
| | | 682 | | private static string NormalizeExportPath(string filePath, ExportFormat fmt) |
| | | 683 | | { |
| | 4 | 684 | | var fileExtension = Path.GetExtension(filePath).ToLowerInvariant(); |
| | | 685 | | switch (fileExtension) |
| | | 686 | | { |
| | | 687 | | case ".pfx": |
| | 2 | 688 | | if (fmt != ExportFormat.Pfx) |
| | | 689 | | { |
| | 0 | 690 | | throw new NotSupportedException( |
| | 0 | 691 | | $"File extension '{fileExtension}' for '{filePath}' is not supported for PFX certificates.") |
| | | 692 | | } |
| | | 693 | | |
| | | 694 | | break; |
| | | 695 | | case ".pem": |
| | 2 | 696 | | if (fmt != ExportFormat.Pem) |
| | | 697 | | { |
| | 0 | 698 | | throw new NotSupportedException( |
| | 0 | 699 | | $"File extension '{fileExtension}' for '{filePath}' is not supported for PEM certificates.") |
| | | 700 | | } |
| | | 701 | | |
| | | 702 | | break; |
| | | 703 | | case "": |
| | | 704 | | // no extension, use the format as the extension |
| | 0 | 705 | | filePath += fmt == ExportFormat.Pfx ? ".pfx" : ".pem"; |
| | 0 | 706 | | break; |
| | | 707 | | default: |
| | 0 | 708 | | throw new NotSupportedException( |
| | 0 | 709 | | $"File extension '{fileExtension}' for '{filePath}' is not supported. Use .pfx or .pem."); |
| | | 710 | | } |
| | 4 | 711 | | return filePath; |
| | | 712 | | } |
| | | 713 | | |
| | | 714 | | /// <summary> |
| | | 715 | | /// Ensures the output directory exists for the specified file path. |
| | | 716 | | /// </summary> |
| | | 717 | | /// <param name="filePath">The file path to check.</param> |
| | | 718 | | private static void EnsureOutputDirectoryExists(string filePath) |
| | | 719 | | { |
| | 4 | 720 | | var dir = Path.GetDirectoryName(filePath); |
| | 4 | 721 | | if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) |
| | | 722 | | { |
| | 0 | 723 | | throw new DirectoryNotFoundException( |
| | 0 | 724 | | $"Directory '{dir}' does not exist. Cannot export certificate to {filePath}."); |
| | | 725 | | } |
| | 4 | 726 | | } |
| | | 727 | | |
| | | 728 | | /// <summary> |
| | | 729 | | /// Represents the password shapes used for exporting certificates. |
| | | 730 | | /// </summary> |
| | 4 | 731 | | private sealed class PasswordShapes(SecureString? secure, char[]? chars) : IDisposable |
| | | 732 | | { |
| | 10 | 733 | | public SecureString? Secure { get; } = secure; |
| | 14 | 734 | | public char[]? Chars { get; } = chars; |
| | | 735 | | |
| | | 736 | | public void Dispose() |
| | | 737 | | { |
| | | 738 | | try |
| | | 739 | | { |
| | 4 | 740 | | Secure?.Dispose(); |
| | 3 | 741 | | } |
| | | 742 | | finally |
| | | 743 | | { |
| | 4 | 744 | | if (Chars is not null) |
| | | 745 | | { |
| | 3 | 746 | | Array.Clear(Chars, 0, Chars.Length); |
| | | 747 | | } |
| | 4 | 748 | | } |
| | 4 | 749 | | } |
| | | 750 | | } |
| | | 751 | | |
| | | 752 | | /// <summary> |
| | | 753 | | /// Creates password shapes from the provided password span. |
| | | 754 | | /// </summary> |
| | | 755 | | /// <param name="password">The password span.</param> |
| | | 756 | | /// <returns>The created password shapes.</returns> |
| | | 757 | | private static PasswordShapes CreatePasswordShapes(ReadOnlySpan<char> password) |
| | | 758 | | { |
| | 4 | 759 | | var secure = password.IsEmpty ? null : SecureStringUtils.ToSecureString(password); |
| | 4 | 760 | | var chars = password.IsEmpty ? null : password.ToArray(); |
| | 4 | 761 | | return new PasswordShapes(secure, chars); |
| | | 762 | | } |
| | | 763 | | |
| | | 764 | | /// <summary> |
| | | 765 | | /// Exports the specified X509 certificate to a file in the given format. |
| | | 766 | | /// </summary> |
| | | 767 | | /// <param name="cert">The X509Certificate2 to export.</param> |
| | | 768 | | /// <param name="filePath">The file path to export the certificate to.</param> |
| | | 769 | | /// <param name="password">The SecureString password to protect the exported certificate.</param> |
| | | 770 | | private static void ExportPfx(X509Certificate2 cert, string filePath, SecureString? password) |
| | | 771 | | { |
| | 2 | 772 | | var pfx = cert.Export(X509ContentType.Pfx, password); |
| | 2 | 773 | | File.WriteAllBytes(filePath, pfx); |
| | 2 | 774 | | } |
| | | 775 | | |
| | | 776 | | /// <summary> |
| | | 777 | | /// Exports the specified X509 certificate to a file in the given format. |
| | | 778 | | /// </summary> |
| | | 779 | | /// <param name="cert">The X509Certificate2 to export.</param> |
| | | 780 | | /// <param name="filePath">The file path to export the certificate to.</param> |
| | | 781 | | /// <param name="password">The SecureString password to protect the exported certificate.</param> |
| | | 782 | | /// <param name="includePrivateKey">Whether to include the private key in the export.</param> |
| | | 783 | | private static void ExportPem(X509Certificate2 cert, string filePath, ReadOnlySpan<char> password, bool includePriva |
| | | 784 | | { |
| | | 785 | | // Write certificate first, then dispose writer before optional key append to avoid file locks on Windows |
| | 2 | 786 | | using (var sw = new StreamWriter(filePath, false, Encoding.ASCII)) |
| | | 787 | | { |
| | 2 | 788 | | new PemWriter(sw).WriteObject(DotNetUtilities.FromX509Certificate(cert)); |
| | 2 | 789 | | } |
| | | 790 | | |
| | 2 | 791 | | if (includePrivateKey) |
| | | 792 | | { |
| | 1 | 793 | | WritePrivateKey(cert, password, filePath); |
| | | 794 | | // Fallback safeguard: if append was requested but key block missing, try again |
| | | 795 | | try |
| | | 796 | | { |
| | 1 | 797 | | if (ShouldAppendKeyToPem && !File.ReadAllText(filePath).Contains("PRIVATE KEY", StringComparison.Ordinal |
| | | 798 | | { |
| | 0 | 799 | | var baseName = Path.GetFileNameWithoutExtension(filePath); |
| | 0 | 800 | | var dir = Path.GetDirectoryName(filePath); |
| | 0 | 801 | | var keyFile = string.IsNullOrEmpty(dir) ? baseName + ".key" : Path.Combine(dir, baseName + ".key"); |
| | 0 | 802 | | if (File.Exists(keyFile)) |
| | | 803 | | { |
| | 0 | 804 | | File.AppendAllText(filePath, Environment.NewLine + File.ReadAllText(keyFile)); |
| | | 805 | | } |
| | | 806 | | } |
| | 1 | 807 | | } |
| | 0 | 808 | | catch (Exception ex) |
| | | 809 | | { |
| | 0 | 810 | | Log.Debug(ex, "Fallback attempt to append private key to PEM failed"); |
| | 0 | 811 | | } |
| | | 812 | | } |
| | 2 | 813 | | } |
| | | 814 | | |
| | | 815 | | /// <summary> |
| | | 816 | | /// Writes the private key of the specified X509 certificate to a file. |
| | | 817 | | /// </summary> |
| | | 818 | | /// <param name="cert">The X509Certificate2 to export.</param> |
| | | 819 | | /// <param name="password">The SecureString password to protect the exported private key.</param> |
| | | 820 | | /// <param name="certFilePath">The file path to export the certificate to.</param> |
| | | 821 | | private static void WritePrivateKey(X509Certificate2 cert, ReadOnlySpan<char> password, string certFilePath) |
| | | 822 | | { |
| | 1 | 823 | | if (!cert.HasPrivateKey) |
| | | 824 | | { |
| | 0 | 825 | | throw new InvalidOperationException( |
| | 0 | 826 | | "Certificate does not contain a private key; cannot export private key PEM."); |
| | | 827 | | } |
| | | 828 | | |
| | | 829 | | AsymmetricAlgorithm key; |
| | | 830 | | |
| | | 831 | | try |
| | | 832 | | { |
| | | 833 | | // Try RSA first, then ECDSA |
| | 1 | 834 | | key = (AsymmetricAlgorithm?)cert.GetRSAPrivateKey() |
| | 1 | 835 | | ?? cert.GetECDsaPrivateKey() |
| | 1 | 836 | | ?? throw new NotSupportedException( |
| | 1 | 837 | | "Certificate private key is neither RSA nor ECDSA, or is not accessible."); |
| | 1 | 838 | | } |
| | 0 | 839 | | catch (CryptographicException ex) when (ex.HResult == unchecked((int)0x80090016)) |
| | | 840 | | { |
| | | 841 | | // 0x80090016 = NTE_BAD_KEYSET → "Keyset does not exist" |
| | 0 | 842 | | throw new InvalidOperationException( |
| | 0 | 843 | | "The certificate reports a private key, but the key container ('keyset') is not accessible. " + |
| | 0 | 844 | | "This usually means the certificate was loaded without its private key, or the current process " + |
| | 0 | 845 | | "identity does not have permission to access the key. Re-import the certificate from a PFX " + |
| | 0 | 846 | | "with the private key and X509KeyStorageFlags.Exportable, or adjust key permissions.", |
| | 0 | 847 | | ex); |
| | | 848 | | } |
| | | 849 | | |
| | | 850 | | byte[] keyDer; |
| | | 851 | | string pemLabel; |
| | | 852 | | |
| | 1 | 853 | | if (password.IsEmpty) |
| | | 854 | | { |
| | | 855 | | // unencrypted PKCS#8 |
| | 0 | 856 | | keyDer = key switch |
| | 0 | 857 | | { |
| | 0 | 858 | | RSA rsa => rsa.ExportPkcs8PrivateKey(), |
| | 0 | 859 | | ECDsa ecc => ecc.ExportPkcs8PrivateKey(), |
| | 0 | 860 | | _ => throw new NotSupportedException("Only RSA and ECDSA private keys are supported.") |
| | 0 | 861 | | }; |
| | 0 | 862 | | pemLabel = "PRIVATE KEY"; |
| | | 863 | | } |
| | | 864 | | else |
| | | 865 | | { |
| | | 866 | | // encrypted PKCS#8 |
| | 1 | 867 | | var pbe = new PbeParameters( |
| | 1 | 868 | | PbeEncryptionAlgorithm.Aes256Cbc, |
| | 1 | 869 | | HashAlgorithmName.SHA256, |
| | 1 | 870 | | iterationCount: 100_000); |
| | | 871 | | |
| | 1 | 872 | | keyDer = key switch |
| | 1 | 873 | | { |
| | 1 | 874 | | RSA rsa => rsa.ExportEncryptedPkcs8PrivateKey(password, pbe), |
| | 0 | 875 | | ECDsa ecc => ecc.ExportEncryptedPkcs8PrivateKey(password, pbe), |
| | 0 | 876 | | _ => throw new NotSupportedException("Only RSA and ECDSA private keys are supported.") |
| | 1 | 877 | | }; |
| | 1 | 878 | | pemLabel = "ENCRYPTED PRIVATE KEY"; |
| | | 879 | | } |
| | | 880 | | |
| | 1 | 881 | | var keyPem = PemEncoding.WriteString(pemLabel, keyDer); |
| | 1 | 882 | | var certDir = Path.GetDirectoryName(certFilePath); |
| | 1 | 883 | | var baseName = Path.GetFileNameWithoutExtension(certFilePath); |
| | 1 | 884 | | var keyFilePath = string.IsNullOrEmpty(certDir) |
| | 1 | 885 | | ? baseName + ".key" |
| | 1 | 886 | | : Path.Combine(certDir, baseName + ".key"); |
| | | 887 | | |
| | 1 | 888 | | File.WriteAllText(keyFilePath, keyPem); |
| | | 889 | | |
| | | 890 | | try |
| | | 891 | | { |
| | 1 | 892 | | if (ShouldAppendKeyToPem) |
| | | 893 | | { |
| | 0 | 894 | | File.AppendAllText(certFilePath, Environment.NewLine + keyPem); |
| | | 895 | | } |
| | 1 | 896 | | } |
| | 0 | 897 | | catch (Exception ex) |
| | | 898 | | { |
| | 0 | 899 | | Log.Debug(ex, |
| | 0 | 900 | | "Failed to append private key to certificate PEM file {CertFilePath}; continuing with separate key file |
| | 0 | 901 | | certFilePath); |
| | 0 | 902 | | } |
| | 1 | 903 | | } |
| | | 904 | | |
| | | 905 | | /// <summary> |
| | | 906 | | /// Exports the specified X509 certificate to a file in the given format, using a SecureString password and optional |
| | | 907 | | /// </summary> |
| | | 908 | | /// <param name="cert">The X509Certificate2 to export.</param> |
| | | 909 | | /// <param name="filePath">The file path to export the certificate to.</param> |
| | | 910 | | /// <param name="fmt">The export format (Pfx or Pem).</param> |
| | | 911 | | /// <param name="password">The SecureString password to protect the exported certificate or private key, if applicab |
| | | 912 | | /// <param name="includePrivateKey">Whether to include the private key in the export.</param> |
| | | 913 | | public static void Export( |
| | | 914 | | X509Certificate2 cert, |
| | | 915 | | string filePath, |
| | | 916 | | ExportFormat fmt, |
| | | 917 | | SecureString password, |
| | | 918 | | bool includePrivateKey = false) |
| | | 919 | | { |
| | 1 | 920 | | if (password is null) |
| | | 921 | | { |
| | | 922 | | // Delegate to span-based overload with no password |
| | 0 | 923 | | Export(cert, filePath, fmt, [], includePrivateKey); |
| | | 924 | | } |
| | | 925 | | else |
| | | 926 | | { |
| | 1 | 927 | | password.ToSecureSpan(span => |
| | 1 | 928 | | Export(cert, filePath, fmt, span, includePrivateKey) |
| | 1 | 929 | | // this will run your span‐based implementation, |
| | 1 | 930 | | // then immediately zero & free the unmanaged buffer |
| | 1 | 931 | | ); |
| | | 932 | | } |
| | 1 | 933 | | } |
| | | 934 | | |
| | | 935 | | /// <summary> |
| | | 936 | | /// Creates a self-signed certificate from the given RSA JWK JSON and exports it |
| | | 937 | | /// as a PEM certificate (optionally including the private key) to the specified path. |
| | | 938 | | /// </summary> |
| | | 939 | | /// <param name="jwkJson">The RSA JWK JSON string.</param> |
| | | 940 | | /// <param name="filePath"> |
| | | 941 | | /// Target file path. If no extension is provided, ".pem" will be added. |
| | | 942 | | /// </param> |
| | | 943 | | /// <param name="password"> |
| | | 944 | | /// Optional password used to encrypt the private key when <paramref name="includePrivateKey"/> is true. |
| | | 945 | | /// Ignored when <paramref name="includePrivateKey"/> is false. |
| | | 946 | | /// </param> |
| | | 947 | | /// <param name="includePrivateKey"> |
| | | 948 | | /// If true, the PEM export will include the private key (and create a .key file as per Export logic). |
| | | 949 | | /// </param> |
| | | 950 | | public static void ExportPemFromJwkJson( |
| | | 951 | | string jwkJson, |
| | | 952 | | string filePath, |
| | | 953 | | ReadOnlySpan<char> password = default, |
| | | 954 | | bool includePrivateKey = false) |
| | | 955 | | { |
| | 0 | 956 | | if (string.IsNullOrWhiteSpace(jwkJson)) |
| | | 957 | | { |
| | 0 | 958 | | throw new ArgumentException("JWK JSON cannot be null or empty.", nameof(jwkJson)); |
| | | 959 | | } |
| | | 960 | | |
| | | 961 | | // 1) Create a self-signed certificate from the JWK |
| | 0 | 962 | | var cert = CreateSelfSignedCertificateFromJwk(jwkJson); |
| | | 963 | | |
| | | 964 | | // 2) Reuse the existing Export pipeline to write PEM (cert + optional key) |
| | 0 | 965 | | Export(cert, filePath, ExportFormat.Pem, password, includePrivateKey); |
| | 0 | 966 | | } |
| | | 967 | | |
| | | 968 | | /// <summary> |
| | | 969 | | /// Creates a self-signed certificate from the given RSA JWK JSON and exports it |
| | | 970 | | /// as a PEM certificate (optionally including the private key) to the specified path, |
| | | 971 | | /// using a <see cref="SecureString"/> password. |
| | | 972 | | /// </summary> |
| | | 973 | | /// <param name="jwkJson">The RSA JWK JSON string.</param> |
| | | 974 | | /// <param name="filePath">Target file path for the PEM output.</param> |
| | | 975 | | /// <param name="password"> |
| | | 976 | | /// SecureString password used to encrypt the private key when |
| | | 977 | | /// <paramref name="includePrivateKey"/> is true. |
| | | 978 | | /// </param> |
| | | 979 | | /// <param name="includePrivateKey"> |
| | | 980 | | /// If true, the PEM export will include the private key. |
| | | 981 | | /// </param> |
| | | 982 | | public static void ExportPemFromJwkJson( |
| | | 983 | | string jwkJson, |
| | | 984 | | string filePath, |
| | | 985 | | SecureString password, |
| | | 986 | | bool includePrivateKey = false) |
| | | 987 | | { |
| | 0 | 988 | | if (password is null) |
| | | 989 | | { |
| | | 990 | | // Delegate to span-based overload with no password |
| | 0 | 991 | | ExportPemFromJwkJson(jwkJson, filePath, [], includePrivateKey); |
| | 0 | 992 | | return; |
| | | 993 | | } |
| | | 994 | | |
| | 0 | 995 | | password.ToSecureSpan(span => |
| | 0 | 996 | | { |
| | 0 | 997 | | ExportPemFromJwkJson(jwkJson, filePath, span, includePrivateKey); |
| | 0 | 998 | | }); |
| | 0 | 999 | | } |
| | | 1000 | | |
| | | 1001 | | #endregion |
| | | 1002 | | |
| | | 1003 | | #region JWK |
| | | 1004 | | |
| | 0 | 1005 | | private static readonly JsonSerializerOptions s_jwkJsonOptions = new() |
| | 0 | 1006 | | { |
| | 0 | 1007 | | PropertyNamingPolicy = JsonNamingPolicy.CamelCase, |
| | 0 | 1008 | | DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, |
| | 0 | 1009 | | WriteIndented = false |
| | 0 | 1010 | | }; |
| | | 1011 | | |
| | | 1012 | | /// <summary> |
| | | 1013 | | /// Creates a self-signed X509 certificate from the provided RSA JWK JSON string. |
| | | 1014 | | /// </summary> |
| | | 1015 | | /// <param name="jwkJson">The JSON string representing the RSA JWK.</param> |
| | | 1016 | | /// <param name="subjectName">The subject name for the certificate.</param> |
| | | 1017 | | /// <returns>A self-signed X509Certificate2 instance.</returns> |
| | | 1018 | | /// <exception cref="ArgumentException">Thrown when the JWK JSON is invalid.</exception> |
| | | 1019 | | /// <exception cref="NotSupportedException"></exception> |
| | | 1020 | | public static X509Certificate2 CreateSelfSignedCertificateFromJwk( |
| | | 1021 | | string jwkJson, |
| | | 1022 | | string subjectName = "CN=client-jwt") |
| | | 1023 | | { |
| | 0 | 1024 | | var jwk = JsonSerializer.Deserialize<RsaJwk>(jwkJson) |
| | 0 | 1025 | | ?? throw new ArgumentException("Invalid JWK JSON"); |
| | | 1026 | | |
| | 0 | 1027 | | if (!string.Equals(jwk.Kty, "RSA", StringComparison.OrdinalIgnoreCase)) |
| | | 1028 | | { |
| | 0 | 1029 | | throw new NotSupportedException("Only RSA JWKs are supported."); |
| | | 1030 | | } |
| | | 1031 | | |
| | 0 | 1032 | | var rsaParams = new RSAParameters |
| | 0 | 1033 | | { |
| | 0 | 1034 | | Modulus = Base64UrlEncoder.DecodeBytes(jwk.N), |
| | 0 | 1035 | | Exponent = Base64UrlEncoder.DecodeBytes(jwk.E), |
| | 0 | 1036 | | D = Base64UrlEncoder.DecodeBytes(jwk.D), |
| | 0 | 1037 | | P = Base64UrlEncoder.DecodeBytes(jwk.P), |
| | 0 | 1038 | | Q = Base64UrlEncoder.DecodeBytes(jwk.Q), |
| | 0 | 1039 | | DP = Base64UrlEncoder.DecodeBytes(jwk.DP), |
| | 0 | 1040 | | DQ = Base64UrlEncoder.DecodeBytes(jwk.DQ), |
| | 0 | 1041 | | InverseQ = Base64UrlEncoder.DecodeBytes(jwk.QI) |
| | 0 | 1042 | | }; |
| | | 1043 | | |
| | 0 | 1044 | | using var rsa = RSA.Create(); |
| | 0 | 1045 | | rsa.ImportParameters(rsaParams); |
| | | 1046 | | |
| | 0 | 1047 | | var req = new CertificateRequest( |
| | 0 | 1048 | | subjectName, |
| | 0 | 1049 | | rsa, |
| | 0 | 1050 | | HashAlgorithmName.SHA256, |
| | 0 | 1051 | | RSASignaturePadding.Pkcs1); |
| | | 1052 | | |
| | | 1053 | | // Self-signed, 1 year validity (tune as you like) |
| | 0 | 1054 | | var notBefore = DateTimeOffset.UtcNow.AddDays(-1); |
| | 0 | 1055 | | var notAfter = notBefore.AddYears(1); |
| | | 1056 | | |
| | 0 | 1057 | | var cert = req.CreateSelfSigned(notBefore, notAfter); |
| | | 1058 | | |
| | | 1059 | | // Export with private key, re-import as X509Certificate2 |
| | 0 | 1060 | | var pfxBytes = cert.Export(X509ContentType.Pfx); |
| | | 1061 | | #if NET9_0_OR_GREATER |
| | | 1062 | | return X509CertificateLoader.LoadPkcs12( |
| | | 1063 | | pfxBytes, |
| | | 1064 | | password: default, |
| | | 1065 | | keyStorageFlags: X509KeyStorageFlags.Exportable, |
| | | 1066 | | loaderLimits: Pkcs12LoaderLimits.Defaults); |
| | | 1067 | | #else |
| | 0 | 1068 | | return new X509Certificate2(pfxBytes, (string?)null, |
| | 0 | 1069 | | X509KeyStorageFlags.Exportable); |
| | | 1070 | | #endif |
| | 0 | 1071 | | } |
| | | 1072 | | |
| | | 1073 | | /// <summary> |
| | | 1074 | | /// Builds a Private Key JWT for client authentication using the specified certificate. |
| | | 1075 | | /// </summary> |
| | | 1076 | | /// <param name="key">The security key (X509SecurityKey or JsonWebKey) to sign the JWT.</param> |
| | | 1077 | | /// <param name="clientId">The client ID (issuer and subject) for the JWT.</param> |
| | | 1078 | | /// <param name="tokenEndpoint">The token endpoint URL (audience) for the JWT.</param> |
| | | 1079 | | /// <returns>The generated Private Key JWT as a string.</returns> |
| | | 1080 | | public static string BuildPrivateKeyJwt( |
| | | 1081 | | SecurityKey key, |
| | | 1082 | | string clientId, |
| | | 1083 | | string tokenEndpoint) |
| | | 1084 | | { |
| | 0 | 1085 | | var now = DateTimeOffset.UtcNow; |
| | | 1086 | | |
| | 0 | 1087 | | var creds = new SigningCredentials(key, SecurityAlgorithms.RsaSha256); |
| | 0 | 1088 | | var handler = new JsonWebTokenHandler(); |
| | | 1089 | | |
| | 0 | 1090 | | var descriptor = new SecurityTokenDescriptor |
| | 0 | 1091 | | { |
| | 0 | 1092 | | Issuer = clientId, |
| | 0 | 1093 | | Audience = tokenEndpoint, |
| | 0 | 1094 | | Subject = new ClaimsIdentity( |
| | 0 | 1095 | | [ |
| | 0 | 1096 | | new Claim("sub", clientId), |
| | 0 | 1097 | | new Claim("jti", Guid.NewGuid().ToString("N")) |
| | 0 | 1098 | | ]), |
| | 0 | 1099 | | NotBefore = now.UtcDateTime, |
| | 0 | 1100 | | IssuedAt = now.UtcDateTime, |
| | 0 | 1101 | | Expires = now.AddMinutes(2).UtcDateTime, |
| | 0 | 1102 | | SigningCredentials = creds |
| | 0 | 1103 | | }; |
| | | 1104 | | |
| | 0 | 1105 | | return handler.CreateToken(descriptor); |
| | | 1106 | | } |
| | | 1107 | | |
| | | 1108 | | /// <summary> |
| | | 1109 | | /// Builds a Private Key JWT for client authentication using the specified X509 certificate. |
| | | 1110 | | /// </summary> |
| | | 1111 | | /// <param name="certificate">The X509 certificate containing the private key.</param> |
| | | 1112 | | /// <param name="clientId">The client ID (issuer and subject) for the JWT.</param> |
| | | 1113 | | /// <param name="tokenEndpoint">The token endpoint URL (audience) for the JWT.</param> |
| | | 1114 | | /// <returns>The generated Private Key JWT as a string.</returns> |
| | | 1115 | | public static string BuildPrivateKeyJwt( |
| | | 1116 | | X509Certificate2 certificate, |
| | | 1117 | | string clientId, |
| | | 1118 | | string tokenEndpoint) |
| | | 1119 | | { |
| | 0 | 1120 | | var key = new X509SecurityKey(certificate) |
| | 0 | 1121 | | { |
| | 0 | 1122 | | KeyId = certificate.Thumbprint |
| | 0 | 1123 | | }; |
| | | 1124 | | |
| | 0 | 1125 | | return BuildPrivateKeyJwt(key, clientId, tokenEndpoint); |
| | | 1126 | | } |
| | | 1127 | | |
| | | 1128 | | /// <summary> |
| | | 1129 | | /// Builds a Private Key JWT for client authentication using the specified JWK JSON string. |
| | | 1130 | | /// </summary> |
| | | 1131 | | /// <param name="jwkJson">The JWK JSON string representing the key.</param> |
| | | 1132 | | /// <param name="clientId">The client ID (issuer and subject) for the JWT.</param> |
| | | 1133 | | /// <param name="tokenEndpoint">The token endpoint URL (audience) for the JWT.</param> |
| | | 1134 | | /// <returns>The generated Private Key JWT as a string.</returns> |
| | | 1135 | | public static string BuildPrivateKeyJwtFromJwkJson( |
| | | 1136 | | string jwkJson, |
| | | 1137 | | string clientId, |
| | | 1138 | | string tokenEndpoint) |
| | | 1139 | | { |
| | 0 | 1140 | | var jwk = new JsonWebKey(jwkJson); |
| | | 1141 | | // You can set KeyId here if you want to use kid from the JSON: |
| | | 1142 | | // jwk.KeyId is automatically populated from "kid" if present. |
| | | 1143 | | |
| | 0 | 1144 | | return BuildPrivateKeyJwt(jwk, clientId, tokenEndpoint); |
| | | 1145 | | } |
| | | 1146 | | |
| | | 1147 | | /// <summary> |
| | | 1148 | | /// Builds a JWK JSON (RSA) representation of the given certificate. |
| | | 1149 | | /// By default only public parameters are included (safe for publishing as JWKS). |
| | | 1150 | | /// Set <paramref name="includePrivateParameters"/> to true if you want a full private JWK |
| | | 1151 | | /// (for local storage only – never publish it). |
| | | 1152 | | /// </summary> |
| | | 1153 | | /// <param name="certificate">The X509 certificate to convert.</param> |
| | | 1154 | | /// <param name="includePrivateParameters">Whether to include private key parameters in the JWK.</param> |
| | | 1155 | | /// <returns>The JWK JSON string.</returns> |
| | | 1156 | | public static string CreateJwkJsonFromCertificate( |
| | | 1157 | | X509Certificate2 certificate, |
| | | 1158 | | bool includePrivateParameters = false) |
| | | 1159 | | { |
| | 0 | 1160 | | var x509Key = new X509SecurityKey(certificate) |
| | 0 | 1161 | | { |
| | 0 | 1162 | | KeyId = certificate.Thumbprint?.ToLowerInvariant() |
| | 0 | 1163 | | }; |
| | | 1164 | | |
| | | 1165 | | // Convert to a JsonWebKey (n, e, kid, x5c, etc.) |
| | 0 | 1166 | | var jwk = JsonWebKeyConverter.ConvertFromX509SecurityKey( |
| | 0 | 1167 | | x509Key, |
| | 0 | 1168 | | representAsRsaKey: true); |
| | | 1169 | | |
| | 0 | 1170 | | if (!includePrivateParameters) |
| | | 1171 | | { |
| | | 1172 | | // Clean public JWK |
| | 0 | 1173 | | jwk.D = null; |
| | 0 | 1174 | | jwk.P = null; |
| | 0 | 1175 | | jwk.Q = null; |
| | 0 | 1176 | | jwk.DP = null; |
| | 0 | 1177 | | jwk.DQ = null; |
| | 0 | 1178 | | jwk.QI = null; |
| | | 1179 | | } |
| | | 1180 | | else |
| | | 1181 | | { |
| | 0 | 1182 | | if (!certificate.HasPrivateKey) |
| | | 1183 | | { |
| | 0 | 1184 | | throw new InvalidOperationException("Certificate has no private key."); |
| | | 1185 | | } |
| | | 1186 | | |
| | 0 | 1187 | | using var rsa = certificate.GetRSAPrivateKey() |
| | 0 | 1188 | | ?? throw new NotSupportedException("Certificate does not contain an RSA private key."); |
| | | 1189 | | |
| | 0 | 1190 | | var p = rsa.ExportParameters(true); |
| | | 1191 | | |
| | 0 | 1192 | | jwk.N = Base64UrlEncoder.Encode(p.Modulus); |
| | 0 | 1193 | | jwk.E = Base64UrlEncoder.Encode(p.Exponent); |
| | 0 | 1194 | | jwk.D = Base64UrlEncoder.Encode(p.D); |
| | 0 | 1195 | | jwk.P = Base64UrlEncoder.Encode(p.P); |
| | 0 | 1196 | | jwk.Q = Base64UrlEncoder.Encode(p.Q); |
| | 0 | 1197 | | jwk.DP = Base64UrlEncoder.Encode(p.DP); |
| | 0 | 1198 | | jwk.DQ = Base64UrlEncoder.Encode(p.DQ); |
| | 0 | 1199 | | jwk.QI = Base64UrlEncoder.Encode(p.InverseQ); |
| | | 1200 | | } |
| | | 1201 | | |
| | 0 | 1202 | | return JsonSerializer.Serialize(jwk, s_jwkJsonOptions); |
| | | 1203 | | } |
| | | 1204 | | |
| | | 1205 | | /// <summary> |
| | | 1206 | | /// Creates an RSA JWK JSON from a given RSA instance (must contain private key). |
| | | 1207 | | /// </summary> |
| | | 1208 | | /// <param name="rsa">The RSA instance with a private key.</param> |
| | | 1209 | | /// <param name="keyId">Optional key identifier (kid) to set on the JWK.</param> |
| | | 1210 | | /// <returns>JWK JSON string containing public and private parameters.</returns> |
| | | 1211 | | public static string CreateJwkJsonFromRsa(RSA rsa, string? keyId = null) |
| | | 1212 | | { |
| | 0 | 1213 | | ArgumentNullException.ThrowIfNull(rsa); |
| | | 1214 | | |
| | | 1215 | | // true => includes private key params (d, p, q, dp, dq, qi) |
| | 0 | 1216 | | var p = rsa.ExportParameters(includePrivateParameters: true); |
| | | 1217 | | |
| | 0 | 1218 | | if (p.D is null || p.P is null || p.Q is null || |
| | 0 | 1219 | | p.DP is null || p.DQ is null || p.InverseQ is null) |
| | | 1220 | | { |
| | 0 | 1221 | | throw new InvalidOperationException("RSA key does not contain private parameters."); |
| | | 1222 | | } |
| | | 1223 | | |
| | 0 | 1224 | | var jwk = new RsaJwk |
| | 0 | 1225 | | { |
| | 0 | 1226 | | Kty = "RSA", |
| | 0 | 1227 | | N = Base64UrlEncoder.Encode(p.Modulus), |
| | 0 | 1228 | | E = Base64UrlEncoder.Encode(p.Exponent), |
| | 0 | 1229 | | D = Base64UrlEncoder.Encode(p.D), |
| | 0 | 1230 | | P = Base64UrlEncoder.Encode(p.P), |
| | 0 | 1231 | | Q = Base64UrlEncoder.Encode(p.Q), |
| | 0 | 1232 | | DP = Base64UrlEncoder.Encode(p.DP), |
| | 0 | 1233 | | DQ = Base64UrlEncoder.Encode(p.DQ), |
| | 0 | 1234 | | QI = Base64UrlEncoder.Encode(p.InverseQ), |
| | 0 | 1235 | | Kid = keyId |
| | 0 | 1236 | | }; |
| | | 1237 | | |
| | 0 | 1238 | | return JsonSerializer.Serialize(jwk, s_jwkJsonOptions); |
| | | 1239 | | } |
| | | 1240 | | |
| | | 1241 | | /// <summary> |
| | | 1242 | | /// Creates an RSA JWK JSON from a PKCS#1 or PKCS#8 RSA private key in PEM format. |
| | | 1243 | | /// </summary> |
| | | 1244 | | /// <param name="rsaPrivateKeyPem"> |
| | | 1245 | | /// PEM containing an RSA private key (e.g. "-----BEGIN RSA PRIVATE KEY----- ..."). |
| | | 1246 | | /// </param> |
| | | 1247 | | /// <param name="keyId">Optional key identifier (kid) to set on the JWK.</param> |
| | | 1248 | | /// <returns>JWK JSON string containing public and private parameters.</returns> |
| | | 1249 | | public static string CreateJwkJsonFromRsaPrivateKeyPem( |
| | | 1250 | | string rsaPrivateKeyPem, |
| | | 1251 | | string? keyId = null) |
| | | 1252 | | { |
| | 0 | 1253 | | if (string.IsNullOrWhiteSpace(rsaPrivateKeyPem)) |
| | | 1254 | | { |
| | 0 | 1255 | | throw new ArgumentException("RSA private key PEM cannot be null or empty.", nameof(rsaPrivateKeyPem)); |
| | | 1256 | | } |
| | | 1257 | | |
| | 0 | 1258 | | using var rsa = RSA.Create(); |
| | 0 | 1259 | | rsa.ImportFromPem(rsaPrivateKeyPem.AsSpan()); |
| | | 1260 | | |
| | 0 | 1261 | | return CreateJwkJsonFromRsa(rsa, keyId); |
| | 0 | 1262 | | } |
| | | 1263 | | |
| | | 1264 | | #endregion |
| | | 1265 | | |
| | | 1266 | | #region Validation helpers (Test-PodeCertificate equivalent) |
| | | 1267 | | /// <summary> |
| | | 1268 | | /// Validates the specified X509 certificate according to the provided options. |
| | | 1269 | | /// </summary> |
| | | 1270 | | /// <param name="cert">The X509Certificate2 to validate.</param> |
| | | 1271 | | /// <param name="checkRevocation">Whether to check certificate revocation status.</param> |
| | | 1272 | | /// <param name="allowWeakAlgorithms">Whether to allow weak algorithms such as SHA-1 or small key sizes.</param> |
| | | 1273 | | /// <param name="denySelfSigned">Whether to deny self-signed certificates.</param> |
| | | 1274 | | /// <param name="expectedPurpose">A collection of expected key purposes (EKU) for the certificate.</param> |
| | | 1275 | | /// <param name="strictPurpose">If true, the certificate must match the expected purposes exactly.</param> |
| | | 1276 | | /// <returns>True if the certificate is valid according to the specified options; otherwise, false.</returns> |
| | | 1277 | | public static bool Validate( |
| | | 1278 | | X509Certificate2 cert, |
| | | 1279 | | bool checkRevocation = false, |
| | | 1280 | | bool allowWeakAlgorithms = false, |
| | | 1281 | | bool denySelfSigned = false, |
| | | 1282 | | OidCollection? expectedPurpose = null, |
| | | 1283 | | bool strictPurpose = false) |
| | | 1284 | | { |
| | | 1285 | | // 1) Validity period |
| | 7 | 1286 | | if (!IsWithinValidityPeriod(cert)) |
| | | 1287 | | { |
| | 0 | 1288 | | return false; |
| | | 1289 | | } |
| | | 1290 | | |
| | | 1291 | | // 2) Self-signed policy |
| | 7 | 1292 | | var isSelfSigned = cert.Subject == cert.Issuer; |
| | 7 | 1293 | | if (denySelfSigned && isSelfSigned) |
| | | 1294 | | { |
| | 1 | 1295 | | return false; |
| | | 1296 | | } |
| | | 1297 | | |
| | | 1298 | | // Pre-compute weakness so we can apply it consistently across validation steps. |
| | 6 | 1299 | | var isWeak = UsesWeakAlgorithms(cert); |
| | | 1300 | | |
| | | 1301 | | // 3) Chain build (with optional revocation) |
| | 6 | 1302 | | if (!BuildChainOk(cert, checkRevocation, isSelfSigned, allowWeakAlgorithms, isWeak)) |
| | | 1303 | | { |
| | 0 | 1304 | | return false; |
| | | 1305 | | } |
| | | 1306 | | |
| | | 1307 | | // 4) EKU / purposes |
| | 6 | 1308 | | if (!PurposesOk(cert, expectedPurpose, strictPurpose)) |
| | | 1309 | | { |
| | 1 | 1310 | | return false; |
| | | 1311 | | } |
| | | 1312 | | |
| | | 1313 | | // 5) Weak algorithms |
| | 5 | 1314 | | if (!allowWeakAlgorithms && isWeak) |
| | | 1315 | | { |
| | 1 | 1316 | | return false; |
| | | 1317 | | } |
| | | 1318 | | |
| | 4 | 1319 | | return true; // ✅ everything passed |
| | | 1320 | | } |
| | | 1321 | | |
| | | 1322 | | /// <summary> |
| | | 1323 | | /// Checks if the certificate is within its validity period. |
| | | 1324 | | /// </summary> |
| | | 1325 | | /// <param name="cert">The X509Certificate2 to check.</param> |
| | | 1326 | | /// <returns>True if the certificate is within its validity period; otherwise, false.</returns> |
| | | 1327 | | private static bool IsWithinValidityPeriod(X509Certificate2 cert) |
| | | 1328 | | { |
| | 7 | 1329 | | var notBeforeUtc = cert.NotBefore.Kind == DateTimeKind.Utc |
| | 7 | 1330 | | ? cert.NotBefore |
| | 7 | 1331 | | : cert.NotBefore.ToUniversalTime(); |
| | | 1332 | | |
| | 7 | 1333 | | var notAfterUtc = cert.NotAfter.Kind == DateTimeKind.Utc |
| | 7 | 1334 | | ? cert.NotAfter |
| | 7 | 1335 | | : cert.NotAfter.ToUniversalTime(); |
| | | 1336 | | |
| | 7 | 1337 | | var nowUtc = DateTime.UtcNow; |
| | 7 | 1338 | | return nowUtc >= notBeforeUtc && nowUtc <= notAfterUtc; |
| | | 1339 | | } |
| | | 1340 | | |
| | | 1341 | | /// <summary> |
| | | 1342 | | /// Checks if the certificate chain is valid. |
| | | 1343 | | /// </summary> |
| | | 1344 | | /// <param name="cert">The X509Certificate2 to check.</param> |
| | | 1345 | | /// <param name="checkRevocation">Whether to check certificate revocation status.</param> |
| | | 1346 | | /// <param name="isSelfSigned">Whether the certificate is self-signed.</param> |
| | | 1347 | | /// <returns>True if the certificate chain is valid; otherwise, false.</returns> |
| | | 1348 | | private static bool BuildChainOk(X509Certificate2 cert, bool checkRevocation, bool isSelfSigned) |
| | | 1349 | | { |
| | 5 | 1350 | | using var chain = new X509Chain(); |
| | 5 | 1351 | | chain.ChainPolicy.RevocationMode = checkRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck; |
| | 5 | 1352 | | chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EndCertificateOnly; |
| | 5 | 1353 | | chain.ChainPolicy.DisableCertificateDownloads = !checkRevocation; |
| | | 1354 | | |
| | 5 | 1355 | | if (isSelfSigned) |
| | | 1356 | | { |
| | | 1357 | | // Make self-signed validation deterministic across platforms. |
| | | 1358 | | // Using the platform trust store differs between Windows/macOS/Linux; custom root trust |
| | | 1359 | | // avoids false negatives for dev/self-signed certificates. |
| | 5 | 1360 | | chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; |
| | 5 | 1361 | | _ = chain.ChainPolicy.CustomTrustStore.Add(cert); |
| | 5 | 1362 | | chain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag; |
| | | 1363 | | } |
| | | 1364 | | |
| | 5 | 1365 | | var ok = chain.Build(cert); |
| | 5 | 1366 | | if (ok) |
| | | 1367 | | { |
| | 5 | 1368 | | return true; |
| | | 1369 | | } |
| | | 1370 | | |
| | 0 | 1371 | | if (!isSelfSigned) |
| | | 1372 | | { |
| | 0 | 1373 | | return false; |
| | | 1374 | | } |
| | | 1375 | | |
| | | 1376 | | // Some platforms still report non-fatal statuses for self-signed roots. |
| | | 1377 | | // Treat these as acceptable for self-signed certificates. |
| | 0 | 1378 | | var allowed = X509ChainStatusFlags.UntrustedRoot | X509ChainStatusFlags.PartialChain; |
| | 0 | 1379 | | if (!checkRevocation) |
| | | 1380 | | { |
| | 0 | 1381 | | allowed |= X509ChainStatusFlags.RevocationStatusUnknown | X509ChainStatusFlags.OfflineRevocation; |
| | | 1382 | | } |
| | | 1383 | | |
| | 0 | 1384 | | var combined = X509ChainStatusFlags.NoError; |
| | 0 | 1385 | | foreach (var status in chain.ChainStatus) |
| | | 1386 | | { |
| | 0 | 1387 | | combined |= status.Status; |
| | | 1388 | | } |
| | | 1389 | | |
| | 0 | 1390 | | return (combined & ~allowed) == 0; |
| | 5 | 1391 | | } |
| | | 1392 | | |
| | | 1393 | | /// <summary> |
| | | 1394 | | /// Checks if the certificate chain is valid. |
| | | 1395 | | /// </summary> |
| | | 1396 | | /// <param name="cert">The X509Certificate2 to check.</param> |
| | | 1397 | | /// <param name="checkRevocation">Whether to check certificate revocation status.</param> |
| | | 1398 | | /// <param name="isSelfSigned">Whether the certificate is self-signed.</param> |
| | | 1399 | | /// <param name="allowWeakAlgorithms">Whether weak algorithms are allowed.</param> |
| | | 1400 | | /// <param name="isWeak">Whether the certificate is considered weak by this library.</param> |
| | | 1401 | | /// <returns>True if the certificate chain is valid; otherwise, false.</returns> |
| | | 1402 | | private static bool BuildChainOk( |
| | | 1403 | | X509Certificate2 cert, |
| | | 1404 | | bool checkRevocation, |
| | | 1405 | | bool isSelfSigned, |
| | | 1406 | | bool allowWeakAlgorithms, |
| | 6 | 1407 | | bool isWeak) => (isSelfSigned && allowWeakAlgorithms && isWeak) || BuildChainOk(cert, checkRevocation, isSelfSig |
| | | 1408 | | |
| | | 1409 | | /// <summary> |
| | | 1410 | | /// Checks if the certificate has the expected key purposes (EKU). |
| | | 1411 | | /// </summary> |
| | | 1412 | | /// <param name="cert">The X509Certificate2 to check.</param> |
| | | 1413 | | /// <param name="expectedPurpose">A collection of expected key purposes (EKU) for the certificate.</param> |
| | | 1414 | | /// <param name="strictPurpose">If true, the certificate must match the expected purposes exactly.</param> |
| | | 1415 | | /// <returns>True if the certificate has the expected purposes; otherwise, false.</returns> |
| | | 1416 | | private static bool PurposesOk(X509Certificate2 cert, OidCollection? expectedPurpose, bool strictPurpose) |
| | | 1417 | | { |
| | 6 | 1418 | | if (expectedPurpose is not { Count: > 0 }) |
| | | 1419 | | { |
| | 3 | 1420 | | return true; // nothing to check |
| | | 1421 | | } |
| | | 1422 | | |
| | 3 | 1423 | | var eku = GetEkuOids(cert); |
| | 3 | 1424 | | var wanted = expectedPurpose |
| | 3 | 1425 | | .Cast<Oid>() |
| | 4 | 1426 | | .Select(static o => o.Value) |
| | 4 | 1427 | | .Where(static v => !string.IsNullOrWhiteSpace(v)) |
| | 4 | 1428 | | .Select(static v => v!) |
| | 3 | 1429 | | .ToHashSet(StringComparer.Ordinal); |
| | | 1430 | | |
| | 3 | 1431 | | return wanted.Count == 0 || (eku.Count != 0 && (strictPurpose ? eku.SetEquals(wanted) : wanted.IsSubsetOf(eku))) |
| | | 1432 | | } |
| | | 1433 | | |
| | | 1434 | | /// <summary> |
| | | 1435 | | /// Extracts EKU OIDs from the certificate, robustly across platforms. |
| | | 1436 | | /// </summary> |
| | | 1437 | | /// <param name="cert">The certificate to inspect.</param> |
| | | 1438 | | /// <returns>A set of EKU OID strings.</returns> |
| | | 1439 | | private static HashSet<string> GetEkuOids(X509Certificate2 cert) |
| | | 1440 | | { |
| | 3 | 1441 | | var set = new HashSet<string>(StringComparer.Ordinal); |
| | | 1442 | | |
| | | 1443 | | // EKU extension OID |
| | 3 | 1444 | | var ext = cert.Extensions["2.5.29.37"]; |
| | 3 | 1445 | | if (ext == null) |
| | | 1446 | | { |
| | 0 | 1447 | | return set; |
| | | 1448 | | } |
| | | 1449 | | |
| | 3 | 1450 | | var ekuExt = ext as X509EnhancedKeyUsageExtension |
| | 3 | 1451 | | ?? new X509EnhancedKeyUsageExtension(ext, ext.Critical); |
| | | 1452 | | |
| | 18 | 1453 | | foreach (var oid in ekuExt.EnhancedKeyUsages.Cast<Oid>()) |
| | | 1454 | | { |
| | 6 | 1455 | | if (!string.IsNullOrWhiteSpace(oid.Value)) |
| | | 1456 | | { |
| | 6 | 1457 | | _ = set.Add(oid.Value); |
| | | 1458 | | } |
| | | 1459 | | } |
| | | 1460 | | |
| | 3 | 1461 | | return set; |
| | | 1462 | | } |
| | | 1463 | | |
| | | 1464 | | /// <summary> |
| | | 1465 | | /// Checks if the certificate uses weak algorithms. |
| | | 1466 | | /// </summary> |
| | | 1467 | | /// <param name="cert">The X509Certificate2 to check.</param> |
| | | 1468 | | /// <returns>True if the certificate uses weak algorithms; otherwise, false.</returns> |
| | | 1469 | | private static bool UsesWeakAlgorithms(X509Certificate2 cert) |
| | | 1470 | | { |
| | 6 | 1471 | | var isSha1 = cert.SignatureAlgorithm?.FriendlyName? |
| | 6 | 1472 | | .Contains("sha1", StringComparison.OrdinalIgnoreCase) == true; |
| | | 1473 | | |
| | 6 | 1474 | | var weakRsa = cert.GetRSAPublicKey() is { KeySize: < 2048 }; |
| | 6 | 1475 | | var weakDsa = cert.GetDSAPublicKey() is { KeySize: < 2048 }; |
| | 6 | 1476 | | var weakEcdsa = cert.GetECDsaPublicKey() is { KeySize: < 256 }; // P-256 minimum |
| | | 1477 | | |
| | 6 | 1478 | | return isSha1 || weakRsa || weakDsa || weakEcdsa; |
| | | 1479 | | } |
| | | 1480 | | |
| | | 1481 | | /// <summary> |
| | | 1482 | | /// Gets the enhanced key usage purposes (EKU) from the specified X509 certificate. |
| | | 1483 | | /// </summary> |
| | | 1484 | | /// <param name="cert">The X509Certificate2 to extract purposes from.</param> |
| | | 1485 | | /// <returns>An enumerable of purpose names or OID values.</returns> |
| | | 1486 | | public static IEnumerable<string> GetPurposes(X509Certificate2 cert) => |
| | 1 | 1487 | | cert.Extensions |
| | 1 | 1488 | | .OfType<X509EnhancedKeyUsageExtension>() |
| | 1 | 1489 | | .SelectMany(x => x.EnhancedKeyUsages.Cast<Oid>()) |
| | 2 | 1490 | | .Select(o => (o.FriendlyName ?? o.Value)!) // ← null-forgiving |
| | 3 | 1491 | | .Where(s => s.Length > 0); // optional: drop empties |
| | | 1492 | | #endregion |
| | | 1493 | | |
| | | 1494 | | #region private helpers |
| | | 1495 | | private static AsymmetricCipherKeyPair GenRsaKeyPair(int bits, SecureRandom rng) |
| | | 1496 | | { |
| | 13 | 1497 | | var gen = new RsaKeyPairGenerator(); |
| | 13 | 1498 | | gen.Init(new KeyGenerationParameters(rng, bits)); |
| | 13 | 1499 | | return gen.GenerateKeyPair(); |
| | | 1500 | | } |
| | | 1501 | | |
| | | 1502 | | /// <summary> |
| | | 1503 | | /// Generates an EC key pair. |
| | | 1504 | | /// </summary> |
| | | 1505 | | /// <param name="bits">The key size in bits.</param> |
| | | 1506 | | /// <param name="rng">The secure random number generator.</param> |
| | | 1507 | | /// <returns>The generated EC key pair.</returns> |
| | | 1508 | | private static AsymmetricCipherKeyPair GenEcKeyPair(int bits, SecureRandom rng) |
| | | 1509 | | { |
| | | 1510 | | // NIST-style names are fine here |
| | 1 | 1511 | | var name = bits switch |
| | 1 | 1512 | | { |
| | 1 | 1513 | | <= 256 => "P-256", |
| | 0 | 1514 | | <= 384 => "P-384", |
| | 0 | 1515 | | _ => "P-521" |
| | 1 | 1516 | | }; |
| | | 1517 | | |
| | | 1518 | | // ECNamedCurveTable knows about SEC *and* NIST names |
| | 1 | 1519 | | var ecParams = ECNamedCurveTable.GetByName(name) |
| | 1 | 1520 | | ?? throw new InvalidOperationException($"Curve not found: {name}"); |
| | | 1521 | | |
| | 1 | 1522 | | var domain = new ECDomainParameters( |
| | 1 | 1523 | | ecParams.Curve, ecParams.G, ecParams.N, ecParams.H, ecParams.GetSeed()); |
| | | 1524 | | |
| | 1 | 1525 | | var gen = new ECKeyPairGenerator(); |
| | 1 | 1526 | | gen.Init(new ECKeyGenerationParameters(domain, rng)); |
| | 1 | 1527 | | return gen.GenerateKeyPair(); |
| | | 1528 | | } |
| | | 1529 | | |
| | | 1530 | | /// <summary> |
| | | 1531 | | /// Converts a BouncyCastle X509Certificate to a .NET X509Certificate2. |
| | | 1532 | | /// </summary> |
| | | 1533 | | /// <param name="cert">The BouncyCastle X509Certificate to convert.</param> |
| | | 1534 | | /// <param name="privKey">The private key associated with the certificate.</param> |
| | | 1535 | | /// <param name="flags">The key storage flags to use.</param> |
| | | 1536 | | /// <param name="ephemeral">Whether the key is ephemeral.</param> |
| | | 1537 | | /// <returns></returns> |
| | | 1538 | | private static X509Certificate2 ToX509Cert2( |
| | | 1539 | | Org.BouncyCastle.X509.X509Certificate cert, |
| | | 1540 | | AsymmetricKeyParameter privKey, |
| | | 1541 | | X509KeyStorageFlags flags, |
| | | 1542 | | bool ephemeral) |
| | | 1543 | | { |
| | 12 | 1544 | | var store = new Pkcs12StoreBuilder().Build(); |
| | 12 | 1545 | | var entry = new X509CertificateEntry(cert); |
| | | 1546 | | const string alias = "cert"; |
| | 12 | 1547 | | store.SetCertificateEntry(alias, entry); |
| | 12 | 1548 | | store.SetKeyEntry(alias, new AsymmetricKeyEntry(privKey), |
| | 12 | 1549 | | [entry]); |
| | | 1550 | | |
| | 12 | 1551 | | using var ms = new MemoryStream(); |
| | 12 | 1552 | | store.Save(ms, [], new SecureRandom()); |
| | 12 | 1553 | | var raw = ms.ToArray(); |
| | | 1554 | | |
| | | 1555 | | #if NET9_0_OR_GREATER |
| | | 1556 | | try |
| | | 1557 | | { |
| | | 1558 | | return X509CertificateLoader.LoadPkcs12( |
| | | 1559 | | raw, |
| | | 1560 | | password: default, |
| | | 1561 | | keyStorageFlags: flags | (ephemeral ? X509KeyStorageFlags.EphemeralKeySet : 0), |
| | | 1562 | | loaderLimits: Pkcs12LoaderLimits.Defaults |
| | | 1563 | | ); |
| | | 1564 | | } |
| | | 1565 | | catch (PlatformNotSupportedException) when (ephemeral) |
| | | 1566 | | { |
| | | 1567 | | // Some platforms (e.g. certain Linux/macOS runners) don't yet support |
| | | 1568 | | // EphemeralKeySet with the new X509CertificateLoader API. In that case |
| | | 1569 | | // we fall back to re-loading without the EphemeralKeySet flag. The |
| | | 1570 | | // intent of Ephemeral in our API is simply "do not persist in a store" – |
| | | 1571 | | // loading without the flag here still keeps the cert in-memory only. |
| | | 1572 | | Log.Debug("EphemeralKeySet not supported on this platform for X509CertificateLoader; falling back without th |
| | | 1573 | | return X509CertificateLoader.LoadPkcs12( |
| | | 1574 | | raw, |
| | | 1575 | | password: default, |
| | | 1576 | | keyStorageFlags: flags, // omit EphemeralKeySet |
| | | 1577 | | loaderLimits: Pkcs12LoaderLimits.Defaults |
| | | 1578 | | ); |
| | | 1579 | | } |
| | | 1580 | | #else |
| | | 1581 | | try |
| | | 1582 | | { |
| | 12 | 1583 | | return new X509Certificate2( |
| | 12 | 1584 | | raw, |
| | 12 | 1585 | | (string?)null, |
| | 12 | 1586 | | flags | (ephemeral ? X509KeyStorageFlags.EphemeralKeySet : 0) |
| | 12 | 1587 | | ); |
| | | 1588 | | } |
| | 0 | 1589 | | catch (PlatformNotSupportedException) when (ephemeral) |
| | | 1590 | | { |
| | | 1591 | | // macOS (and some Linux distros) under net8 may not support EphemeralKeySet here. |
| | 0 | 1592 | | Log.Debug("EphemeralKeySet not supported on this platform (net8); falling back without the flag."); |
| | 0 | 1593 | | return new X509Certificate2( |
| | 0 | 1594 | | raw, |
| | 0 | 1595 | | (string?)null, |
| | 0 | 1596 | | flags // omit EphemeralKeySet |
| | 0 | 1597 | | ); |
| | | 1598 | | } |
| | | 1599 | | |
| | | 1600 | | #endif |
| | 12 | 1601 | | } |
| | | 1602 | | |
| | | 1603 | | #endregion |
| | | 1604 | | } |