Skip to content

Commit f44038c

Browse files
committed
Added certificate helper
1 parent a99512b commit f44038c

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
}

0 commit comments

Comments
 (0)