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 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 :(得分:12)
这是因为程序与不同的用户一起运行。一个是普通用户,另一个是初创用户。
创建密钥后,其权限仅授予创建者。
因此,您需要更改密钥的权限,以便每个人都可以使用它。
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