Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Security.Cryptography.CryptographicException -object already exist

public RSAKeyPair()
    {
        string keyContainerName="pEncKey"
        CspParameters cspp = new CspParameters();
        cspp.Flags = CspProviderFlags.UseMachineKeyStore;
        cspp.KeyContainerName = keyContainerName;
        try
        {
            m_RSA = new RSACryptoServiceProvider(1024, cspp);
        }
        catch(Exception e){}
    }

what is the reason for throwing following exception:

  System.Security.Cryptography.CryptographicException - object already exist 

stack trace is as follows :

   at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
   at System.Security.Cryptography.Utils._CreateCSP(CspParameters param, Boolean randomKeyContainer, SafeProvHandle& hProv)
   at System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
   at System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle)
   at System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair()
   at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize)
   at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters)
   at XXXXXXXX.Core.RSAKeyPair..ctor(String keyContainerName)
like image 785
DevT Avatar asked Jul 11 '12 10:07

DevT


1 Answers

This happens because the program is running with different users. One with normal user and another with startup user.

When the key is created, its permission is only granted to the creator.

Therefore, you need to change the permission of the key in order that it can be used by everyone.

CspParameters cspParams;
cspParams = new CspParameters(PROVIDER_RSA_FULL);
cspParams.KeyContainerName = CONTAINER_NAME;
cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
cspParams.ProviderName = "Microsoft Strong Cryptographic Provider";

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

cspParams.CryptoKeySecurity = new CryptoKeySecurity();
cspParams.CryptoKeySecurity.SetAccessRule(rule);

for more details ,

http://whowish-programming.blogspot.com/2010/10/systemsecuritycryptographycryptographic.html

like image 82
DevT Avatar answered Oct 21 '22 01:10

DevT