0

As title, I am able to add networkService account to a .pfx certificate I have installed on my local machine. I do not install the .pfx with any password for private key.

Powershell solution:

$cert = Get-ChildItem -Path cert:\LocalMachine\My | ? -FilterScript { $PSItem.Subject -like "*<MyCertMatch>*" }   
$keyPath = Join-Path -Path $env:ProgramData -ChildPath "\Microsoft\Crypto\RSA\MachineKeys"
$keyContainerName = $cert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName
$keyFullPath = Join-Path -Path $keyPath -ChildPath $keyName
# Here I can get-acl: using get-acl and see results

Now when I have the fullPath I can add a new acl. However, this (above) I get stuck on in c#:

if (cert.Subject.Contains("<myCertMatch>"))
{
    RSACryptoServiceProvider rsa = cert.PrivateKey as RSACryptoServiceProvider;
    if (rsa != null)
    {
        // Add logic here
    }
}

Here rsa defaults to null but cert.PrivateKey is not null, thus I cannot retrieve container or any ACL.

I'd appreciate any input/feedback.

Thanks,

Razoll
  • 107
  • 1
  • 1
  • 7
  • Why are you trying to use `RSACryptoServiceProvider`? Is `if (cert.PrivateKey != null)` not an option? – G42 Feb 07 '21 at 01:33
  • [might be helpful](https://stackoverflow.com/questions/5872868/best-way-to-initiate-rsacryptoserviceprovider-from-x509certificate2), also [this one](https://stackoverflow.com/questions/55949510/casting-private-key-to-rsacryptoserviceprovider-not-working) but I think less likely – G42 Feb 07 '21 at 01:47
  • 1
    I am using RSACryptoServiceProvider because I am trying to get container name: rsa.CspKeyContainerInfo.UniqueKeyContainerName – Razoll Feb 07 '21 at 01:51
  • have you had any success with the solutions in the linked post? – G42 Feb 07 '21 at 02:17
  • No, unfortunately – Razoll Feb 07 '21 at 02:52
  • Hmm, I gave this a go and things worked as expected... I'm wondering if the problem is upstream. Can you post the code before this part? I assume no wildcards in ``? Might be worth using `Console.WriteLine` or debugger to check your code prior to `RSACryptoServiceProvider rsa` is doing what you want if you haven't already. – G42 Feb 07 '21 at 03:49
  • Note sure if [this](https://www.pkisolutions.com/accessing-and-using-certificate-private-keys-in-net-framework-net-core/) can be helpful but it talks about using `cert.GetRSAPrivateKey()` rather than casting the private key to RSACryptoServiceProvider – Daniel Feb 07 '21 at 04:28
  • Access to `X509Certificate2.PrivateKey` property is obsolete since .NET 4.6. Use corresponding extension method instead: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509certificate2?view=net-5.0#extension-methods – Crypt32 Feb 07 '21 at 09:49

0 Answers0