【发布时间】:2013-11-25 19:33:30
【问题描述】:
我正在编写一个简单的示例代码来演示如何使用 X509 证书进行加密和解密。
public static byte[] Encrypt(byte[] content, X509Certificate2Collection encryptingCertificates)
{
if (content == null)
{
throw new ApplicationException("NullContent");
}
if (encryptingCertificates == null || encryptingCertificates.Count == 0)
{
throw new ApplicationException("NoCertificates");
}
CmsRecipientCollection recipients = new CmsRecipientCollection(SubjectIdentifierType.IssuerAndSerialNumber, encryptingCertificates);
EnvelopedCms dataEnvelope = new EnvelopedCms(new ContentInfo(new Oid("1.2.840.113549.1.7.1"), content), new AlgorithmIdentifier(new Oid("2.16.840.1.101.3.4.1.2")));
dataEnvelope.Encrypt(recipients);
return dataEnvelope.Encode();
}
public static byte[] Decrypt(byte[] encryptedContent, X509Certificate2Collection decryptingCertificates)
{
if (decryptingCertificates == null || decryptingCertificates.Count == 0)
{
throw new ApplicationException("NoCertificates");
}
EnvelopedCms dataEnvelope = new EnvelopedCms();
dataEnvelope.Decode(encryptedContent);
dataEnvelope.Decrypt(decryptingCertificates);
ContentInfo contentInfo = dataEnvelope.ContentInfo;
return contentInfo.Content;
}
我遇到了一个问题 - 必须解密的代码 (dataEnvelope.Decrypt(decryptingCertificates)) 抛出 CryptographicException: Access denied。
CryptographicException: Access denied.
at System.Security.Cryptography.Pkcs.EnvelopedCms.DecryptContent(RecipientInfoCollection recipientInfos, X509Certificate2Collection extraStore)
at CertificateTestingTool.CertificateResolver.Decrypt(Byte[] encryptedContent, X509Certificate2Collection decryptingCerti
ficates)
at CertificateTestingTool.Program.Main(String[] args)
它发生在 windows server 2012 和 windows 8 上。 我在 win server 2008 上检查了这段代码,win 7 运行良好。
补充信息:我不使用 PKI,我从文件夹 (X509Certificate2Collection.Import(…)) 中导入 *.pfx 文件,并导入成功。
public static X509Certificate2Collection GetCertificates(string certPath, string password)
{
X509Certificate2Collection certs = null;
var logger = Log.Logger;
certs = new X509Certificate2Collection();
var flags = X509KeyStorageFlags.DefaultKeySet;
certs.Import(certPath, password, flags);
return certs;
}
有人可以帮我解决这个问题吗?据我了解,新操作系统版本引入了一些权限规则。
【问题讨论】:
-
你的代码在做什么,请把
CertificateTestingTool.CertificateResolver.Decrypt中的代码贴出来 -
我在帖子中添加了附加信息。
-
我们只需要确保 pfx 文件的 KeySpec 设置为 1 (AT_KEYEXCHANGE)。要检查这一点,我们可以使用命令 certutil.exe -dump -v xyz.pfx 当我们使用指定了 KeySpec AT_KEYEXCHANGE 的 certutil 导入 pfx 时,我们正在修改 pfx 文件的 KeySpec 属性。之后,我们可以再次将其导出为pfx文件,然后我们可以使用上面提到的命令再次检查KeySpec,我们会看到KeySpec更改为AT_KEYEXCHANGE。
标签: .net cryptography x509certificate windows-server-2012 pkcs#12