.net - System.Security.Cryptography.CryptographicException - 对象已存在

标签 .net c#-4.0 encryption rsa

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)

最佳答案

发生这种情况是因为程序正在由不同的用户运行。一个是普通用户,另一个是启动用户。

创建 key 后,其权限仅授予创建者。

因此,您需要更改 key 的权限,以便所有人都可以使用。

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

关于.net - System.Security.Cryptography.CryptographicException - 对象已存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11430966/

相关文章:

c# - 分数字体

asp.net-mvc-3 - 具有代码优先独立关联或外键关联的 EF 模型

c# - ScreenCaptureJob 类的引用或程序集

c# - 如何将数据从一个用户控件传递给另一个用户控件都放在default.aspx中

c++ - 在 HElib 上使用 AES 实现; addCtxt 函数失败

java - RSA 加密 Java/Kotlin

c# - 如何对字典中的所有项目求平均值并按键求平均值

c# - 文件流.ReadByte : Byte's are never negative numbers?

.net - 如果没有明确定义,aspnetcore 中服务的默认生命周期是多少?

java - 为什么要随机生成 aes key ?