我正在尝试使用CLR-Security库Security.Cryptography.dll(他们的主页:http://clrsecurity.codeplex.com)
创建一个自签名证书我可以创建证书,甚至可以用它加密, 但Decrypt失败并出现以下错误“指定的提供程序类型无效。”
以下是证书创建代码:
public static bool generateCertificate(string distinguishedName)
{
// Generate Key
CngKeyCreationParameters keyParams = new CngKeyCreationParameters();
keyParams.KeyCreationOptions = CngKeyCreationOptions.MachineKey | CngKeyCreationOptions.OverwriteExistingKey;
keyParams.KeyUsage = CngKeyUsages.AllUsages; //CngKeyUsages.Decryption | CngKeyUsages.Signing;
keyParams.Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider;
keyParams.ExportPolicy = CngExportPolicies.AllowExport;
CngKey newKey = CngKey.Create(CngAlgorithm2.Rsa, Guid.NewGuid().ToString(), keyParams);
// Init certificate
X509CertificateCreationParameters certParams = new X509CertificateCreationParameters(new X500DistinguishedName(distinguishedName));
certParams.SignatureAlgorithm = X509CertificateSignatureAlgorithm.RsaSha1;
certParams.StartTime = DateTime.Now;
certParams.EndTime = DateTime.Now.AddYears(10);
// Create cert
X509Certificate2 newCert = newKey.CreateSelfSignedCertificate(certParams);
// Save to store
X509Store lmStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
lmStore.Open(OpenFlags.ReadWrite);
lmStore.Add(newCert);
lmStore.Close();
return true;
}
以下是加密方法:
public static byte[] encryptStringPKCS7(string toEncrypt, List<byte[]> recipients)
{
// get bytes from encrypt text
UnicodeEncoding unicode = new UnicodeEncoding();
byte[] msgBytes = unicode.GetBytes(toEncrypt);
// Create the certificate collection of the intended recipients
X509Certificate2Collection recipientsCollection = new X509Certificate2Collection();
foreach (byte[] currCertificate in recipients)
{
recipientsCollection.Add(new X509Certificate2(currCertificate));
}
// Place message in a ContentInfo object.
ContentInfo contentInfo = new ContentInfo(msgBytes);
EnvelopedCms envelopedCms = new EnvelopedCms(contentInfo);
// Formulate a CmsRecipientCollection object that
// represents information about the set of recipients
// to encrypt the message for.
CmsRecipientCollection cmsRecipients = new CmsRecipientCollection(SubjectIdentifierType.IssuerAndSerialNumber, recipientsCollection);
// Encrypt the message for the collection of recipients.
envelopedCms.Encrypt(cmsRecipients);
return envelopedCms.Encode();
}
这是Decrypt方法:
public static string decryptStringPKCS7(byte[] toDecrypt)
{
// Place message in a ContentInfo object.
// This is required to build an EnvelopedCms object.
EnvelopedCms envelopedCms = new EnvelopedCms();
// Decrypt the message
envelopedCms.Decode(toDecrypt);
envelopedCms.Decrypt();
byte[] msgDecrypted = envelopedCms.ContentInfo.Content;
// Decode
string msgClearText = Encoding.Unicode.GetString(msgDecrypted);
return msgClearText;
}
当我使用与makecert.exe创建的证书完全相同的代码时 - 它运行良好。
我使用的makecert命令行是:makecert.exe -sr LocalMachine -ss My -n CN=[SomeDN] -sk [SomeRandomGUID] -sky exchange
我是否需要在创建CngKey或证书时指定一些额外的参数? 或者也许在加密期间传递一些额外的信息?
提前感谢您的帮助!