|
| 1 | +using System.Security.Cryptography; |
| 2 | +using System.Security.Cryptography.X509Certificates; |
| 3 | +using System.Text; |
| 4 | + |
| 5 | +namespace OneIdentity.DevOps.Extensions |
| 6 | +{ |
| 7 | + public static class CertificateExtensions |
| 8 | + { |
| 9 | + public static X509Certificate2 LoadFromBytes(byte[] rawData, string? password = null, X509KeyStorageFlags? keyStorageFlags = null) |
| 10 | + { |
| 11 | + // 1. Detect if the byte array is PKCS12 or PEM |
| 12 | + X509ContentType contentType = X509Certificate2.GetCertContentType(rawData); |
| 13 | + |
| 14 | + if (contentType == X509ContentType.Pkcs12) |
| 15 | + { |
| 16 | + if (keyStorageFlags.HasValue) |
| 17 | + { |
| 18 | + // Use the new .NET 9 Loader for binary PKCS12/PFX |
| 19 | + return X509CertificateLoader.LoadPkcs12(rawData, password, keyStorageFlags.Value); |
| 20 | + } |
| 21 | + else |
| 22 | + { |
| 23 | + // Use the new .NET 9 Loader for binary PKCS12/PFX |
| 24 | + return X509CertificateLoader.LoadPkcs12(rawData, password); |
| 25 | + } |
| 26 | + |
| 27 | + } |
| 28 | + else |
| 29 | + { |
| 30 | + // It's likely PEM (text-based). |
| 31 | + // We convert the bytes to a string to use the PEM parser. |
| 32 | + string pemString = Encoding.UTF8.GetString(rawData); |
| 33 | + |
| 34 | + // 1. Load the public certificate |
| 35 | + var cert = X509CertificateLoader.LoadCertificate(rawData); |
| 36 | + |
| 37 | + // 2. Load the private key if it exists in the string |
| 38 | + if (pemString.Contains("PRIVATE KEY")) |
| 39 | + { |
| 40 | + using var rsa = RSA.Create(); |
| 41 | + // ImportFromPem automatically handles both 'Universal 2' and 'Universal 16' |
| 42 | + rsa.ImportFromPem(pemString); |
| 43 | + |
| 44 | + // 3. Link them together |
| 45 | + return cert.CopyWithPrivateKey(rsa); |
| 46 | + } |
| 47 | + |
| 48 | + return cert; |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | +} |
0 commit comments