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