Search code examples
c#rsacryptoserviceprovider

Error "Keyset does not exist" from creating a RSACryptoServiceProvider


My code

csp = new RSACryptoServiceProvider(cspParms); 

causes the error: "Keyset does not exist".

string keyContainerName = "abcd";
CspParameters cspParms = new CspParameters(24, "Microsoft Enhanced RSA and AES Cryptographic Provider", keyContainerName);
cspParms.Flags = CspProviderFlags.UseExistingKey | CspProviderFlags.UseMachineKeyStore;
            

RSACryptoServiceProvider csp = null;
csp = new RSACryptoServiceProvider(cspParms);

csp = new RSACryptoServiceProvider(cspParms); 

causes error: "Object already exists".

Then I added the three lines below before calling

csp = new RSACryptoServiceProvider(cspParms);

CryptoKeyAccessRule rule = new CryptoKeyAccessRule("everyone", CryptoKeyRights.FullControl, AccessControlType.Allow);
cspParms.CryptoKeySecurity = new CryptoKeySecurity();
cspParms.CryptoKeySecurity.SetAccessRule(rule);

Then I got the error: "Keyset does not exist".

Even I removed the added three lines, I still got the error: Keyset does not exist.


Solution

  • I found the reason.

    If I run as an admin, then there is no these error.

    I was using windows 10, and I made everyone could read/write my users folder. But recently my windows was auto upgraded to win 11. The security setting for the users changed, this caused the trouble.