-
Notifications
You must be signed in to change notification settings - Fork 335
Expand file tree
/
Copy pathCspCertificateFixture.cs
More file actions
63 lines (53 loc) · 2.16 KB
/
Copy pathCspCertificateFixture.cs
File metadata and controls
63 lines (53 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace Microsoft.Data.SqlClient.Tests.Common.Fixtures;
/// <summary>
/// Provides a fixture for working with certificates backed by a Cryptographic Service Provider (CSP).
/// </summary>
/// <remarks>
/// This class creates and manages a certificate stored in the current user's certificate store, along
/// with its associated CSP key path. It is intended to facilitate testing or scenarios requiring temporary
/// certificates.
/// </remarks>
public class CspCertificateFixture : CertificateFixtureBase
{
public CspCertificateFixture()
{
// NOTE: If this constructor throws, xUnit never calls Dispose, so the certificate placed in the
// store (and its persisted CSP key container) would be leaked.
try
{
CspCertificate = CreateCertificate(nameof(CspCertificate), Array.Empty<string>(), Array.Empty<string>(), true);
AddToStore(CspCertificate, StoreLocation.CurrentUser, StoreName.My);
CspCertificatePath = $"{StoreLocation.CurrentUser}/{StoreName.My}/{CspCertificate.Thumbprint}";
CspKeyPath = GetCspPathFromCertificate();
}
catch
{
Dispose();
throw;
}
}
public X509Certificate2 CspCertificate { get; }
public string CspCertificatePath { get; }
public string? CspKeyPath { get; }
private string? GetCspPathFromCertificate()
{
RSA? privateKey = CspCertificate.GetRSAPrivateKey();
if (privateKey is RSACryptoServiceProvider csp)
{
return string.Concat(csp.CspKeyContainerInfo.ProviderName, @"/", csp.CspKeyContainerInfo.KeyContainerName);
}
else if (privateKey is RSACng cng && cng.Key.Provider is not null)
{
return string.Concat(cng.Key.Provider.Provider, @"/", cng.Key.KeyName);
}
else
{
return null;
}
}
}