| | | 1 | | using System.IO; |
| | | 2 | | using System.Security.Cryptography.X509Certificates; |
| | | 3 | | |
| | | 4 | | namespace WireMock.HttpsCertificate |
| | | 5 | | { |
| | | 6 | | internal static class ClientCertificateHelper |
| | | 7 | | { |
| | | 8 | | public static X509Certificate2 GetCertificate(string thumbprintOrSubjectName) |
| | 0 | 9 | | { |
| | 0 | 10 | | X509Store certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine); |
| | | 11 | | try |
| | 0 | 12 | | { |
| | | 13 | | // Certificate must be in the local machine store |
| | 0 | 14 | | certStore.Open(OpenFlags.ReadOnly); |
| | | 15 | | |
| | | 16 | | // Attempt to find by thumbprint first |
| | 0 | 17 | | var matchingCertificates = certStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprintOrSubjec |
| | 0 | 18 | | if (matchingCertificates.Count == 0) |
| | 0 | 19 | | { |
| | | 20 | | // Fallback to subject name |
| | 0 | 21 | | matchingCertificates = certStore.Certificates.Find(X509FindType.FindBySubjectName, thumbprintOrSubje |
| | 0 | 22 | | if (matchingCertificates.Count == 0) |
| | 0 | 23 | | { |
| | | 24 | | // No certificates matched the search criteria. |
| | 0 | 25 | | throw new FileNotFoundException("No certificate found with specified Thumbprint or SubjectName." |
| | | 26 | | } |
| | 0 | 27 | | } |
| | | 28 | | |
| | | 29 | | // Use the first matching certificate. |
| | 0 | 30 | | return matchingCertificates[0]; |
| | | 31 | | } |
| | | 32 | | finally |
| | 0 | 33 | | { |
| | | 34 | | #if NETSTANDARD || NET46 |
| | 0 | 35 | | certStore.Dispose(); |
| | | 36 | | #else |
| | | 37 | | certStore.Close(); |
| | | 38 | | #endif |
| | 0 | 39 | | } |
| | 0 | 40 | | } |
| | | 41 | | } |
| | | 42 | | } |