File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
Eocron.Algorithms/Certificates Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ using System ;
2+ using System . Linq ;
3+ using System . Security . Cryptography ;
4+ using System . Security . Cryptography . X509Certificates ;
5+
6+ namespace Eocron . Algorithms . Certificates
7+ {
8+ public static class CertificateHelper
9+ {
10+ public static X509Certificate2 FindByThumbprint ( string thumbprint )
11+ {
12+ if ( string . IsNullOrWhiteSpace ( thumbprint ) )
13+ throw new ArgumentException ( "Thumbprint cannot be null or whitespace." , nameof ( thumbprint ) ) ;
14+ using var store = new X509Store ( StoreName . My , StoreLocation . CurrentUser ) ;
15+ store . Open ( OpenFlags . ReadOnly ) ;
16+
17+ return store . Certificates . Find ( X509FindType . FindByThumbprint , thumbprint , false ) . Single ( ) ;
18+ }
19+
20+ public static string ExportPrivateKeyToPem ( X509Certificate2 cert )
21+ {
22+ if ( ! cert . HasPrivateKey )
23+ throw new InvalidOperationException ( "No private key found in certificate: " + cert . Subject ) ;
24+
25+ var rsa = cert . GetRSAPrivateKey ( ) ;
26+ if ( rsa is RSACng rsaCng )
27+ {
28+ try
29+ {
30+ var parameters = rsaCng . ExportParameters ( true ) ;
31+ using var rsaTemp = RSA . Create ( ) ;
32+ rsaTemp . ImportParameters ( parameters ) ;
33+ return rsaTemp . ExportPkcs8PrivateKeyPem ( ) ;
34+ }
35+ catch ( Exception ex )
36+ {
37+ throw new InvalidOperationException ( "Private key can't be exported: " + cert . Subject , ex ) ;
38+ }
39+ }
40+
41+ return rsa . ExportPkcs8PrivateKeyPem ( ) ;
42+
43+ }
44+ }
45+ }
You can’t perform that action at this time.
0 commit comments