这里我必须总结一下,因为RSACryptoServiceProvider 引发的异常快使我疯掉了!
代码:


WindowsIdentity wi = Logon(UserName, Password);
if (null != wi) {
WindowsImpersonationContext wic = wi.Impersonate();
CspParameters cp = new CspParameters();
cp.ProviderType = 1;
cp.Flags = CspProviderFlags.UseMachineKeyStore;
cp.KeyNumber = (int)KeyNumber.Exchange;
cp.KeyContainerName = "KEY_1";
RSACryptoServiceProvider csp = new RSACryptoServiceProvider( cp);
this.txtPublicKey.Text = this.PublicKey = csp.ToXmlString(false);
csp.Clear();
wic.Undo();
我最先遇到:
System.Security.Cryptography.CryptographicException,发生位置是aspnet_wp.exe(1128)----------->windows XP
System.Security.Cryptography.CryptographicException,发生位置是w3wp.exe------------------>windows Server 2003
症状:是我用了加密算法后,把应用挂在IIS上,就时不时报如上错。
解决:
- while impersonated and dont clean up the keys of the RSACryptoProvider using the clear method while impersonated.
解决步骤:
- Impersonate user
- Create a new RSACryptoServiceProvider (pair)
- Encrypt or Decrypt your data
- Call clear to release the keys (pair.Clear())
- Undo impersonation
2. 当 RSACryptoProvider 创建了密钥文件但由于权限不足而无法删除该密钥文件时,会导致此错误;
解决:
若要更正此错误,请确认代理服务帐户对“Documents and Settings”文件夹中 RSA 计算机密钥文件夹(例如,C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA)的“完全控制”权限设置为“允许”。
我以为RSA加密解密问题就此终结,结果。。。。
异常:
System.Security.Cryptography.CryptographicException:该项不适于在指定状态下使用。
这个问题这个问题为难死我了!
这个问题是客户机子上出现的,而我身边所有的机子都没有过。
从何下手!客户那里不可以远程访问,就别提调试了。
问问他们的环境有无变化:?
------重装过产品
我想问题就应该出在产品身上,因为我加密的时候,模拟用户是我们公司产品建立的一个帐户。
我又找啊找啊,终于找到了原因!
The most common issue in this area occurs when a local (non-domain) user's
password is administratively reset. On WinXP or 2K3, this causes all data protected
by DPAPI (including user private keys) to be lost; at least until the
password is set back. This is by design, and in fact is an important
security feature
解决:
方案一:将模拟帐户的密码恢复到以前的那个密码;
方案二:C:\Documents and Settings\%userName%\Application Data\Microsoft\的Crypto目录给删掉。
哈哈,问题到此暂时结束了。
如果对你有帮助的话,记得顶一下哈