0

I recently rewrote my application from ASP.Net to ASP.Net Core and since then, reading the private key of a cert fails for me.

This is the code doing that:

public static byte[] DecryptWithCert([NotNull] X509Certificate2 cert, byte[] payload)
{
    using (var rsaPrivateKey = cert.GetRSAPrivateKey())
    {
        return rsaPrivateKey.Decrypt(payload, RSAEncryptionPadding.OaepSHA256);
    }
}

The certificate definitely has a privatekey, as even the cert object shows that. However, reading it turns out to throw this exception:

cert.PrivateKey' threw an exception of type 'Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException

The exception message say:

Keyset couldn't be found

What could be the problem here?

EDIT:

It seems like the problem might be due to ASP.Net Core not running through IIS and possibly missing permissions for accessing that certificates private key now.

I just tested it with a small console app, that one is able to get the PK so the certificate ain't broken.

However, I don't really know what User I would have to add to the permissions to make my Kestrel hosted app read that cert key.

Sossenbinder
  • 4,852
  • 5
  • 35
  • 78
  • Possible duplicate of [CryptographicException 'Keyset does not exist', but only through WCF](https://stackoverflow.com/questions/602345/cryptographicexception-keyset-does-not-exist-but-only-through-wcf) – Mate Mar 30 '19 at 22:26
  • If you got the whole call stack, you can compare the source code, https://github.com/dotnet/corefx/search?q=ToCryptographicException&unscoped_q=ToCryptographicException – Lex Li Mar 31 '19 at 01:36

1 Answers1

0

Okay, I found the problem:

I just added "NETWORK SERVICE" in the certmgr -> All Tasks -> Manage Private keys to the users list.

My problem specifically was that in my initial approach before this post I tried this as well, but somehow Windows still wanted me to type that User in german, given that I recently switched from german to english OS. So it was apparently just a problem regarding the proper naming here.

Sossenbinder
  • 4,852
  • 5
  • 35
  • 78