2012-07-11 38 views
7
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){} 
    } 

什麼是拋出下列異常的原因:System.Security.Cryptography.CryptographicException -object已經存在

System.Security.Cryptography.CryptographicException - object already exist 

堆棧跟蹤如下:

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) 
+0

快速谷歌把這個了:http://pwnedcode.wordpress.com/2008/11/10/fixing-cryptographicexception-%E2%80 %9Cobject-已經存在%E2%80%9D /。你有沒有嘗試修復訪問密鑰容器? – 2012-07-11 17:19:37

+0

@owlstead這是爲asp.net命令行之一。 :( – DevT 2012-07-12 03:38:20

回答

11

這是因爲程序與不同的用戶一起運行。一個用普通用戶,另一個用啓動用戶。

創建密鑰時,其權限僅授予創建者。

因此,您需要更改密鑰的權限才能讓所有人使用。

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); 

瞭解更多詳情,

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