我正在编写一个简单的示例代码来演示如何使用 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:访问被拒绝。
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;
}
有人可以帮我吗?据我了解,在新的操作系统版本中引入了一些权限规则。