[英]How to create a valid, self-signed X509Certificate2 programmatically, not loading from file in .NET Core
[英]How to create self-signed certificate programmatically for WCF service?
我有一個自托管 WCF 服務器作為本地系統帳戶下的 Windows 服務運行。 我正在嘗試在 c# 中以編程方式創建自簽名證書,以便與使用消息級別安全性的 net.tcp 端點一起使用。
我正在使用以下代碼,該代碼非常接近於如何使用 C# 創建自簽名證書中接受的答案? 有一些小的改變試圖解決我的問題。
public static X509Certificate2 CreateSelfSignedCertificate(string subjectName, TimeSpan expirationLength)
{
// create DN for subject and issuer
var dn = new CX500DistinguishedName();
dn.Encode("CN=" + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE);
CX509PrivateKey privateKey = new CX509PrivateKey();
privateKey.ProviderName = "Microsoft Strong Cryptographic Provider";
privateKey.Length = 1024;
privateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE;
privateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_DECRYPT_FLAG | X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_KEY_AGREEMENT_FLAG;
privateKey.MachineContext = true;
privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG;
privateKey.Create();
// Use the stronger SHA512 hashing algorithm
var hashobj = new CObjectId();
hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID,
ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY,
AlgorithmFlags.AlgorithmFlagsNone, "SHA1");
// Create the self signing request
var cert = new CX509CertificateRequestCertificate();
cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, "");
cert.Subject = dn;
cert.Issuer = dn; // the issuer and the subject are the same
cert.NotBefore = DateTime.Now.Date;
// this cert expires immediately. Change to whatever makes sense for you
cert.NotAfter = cert.NotBefore + expirationLength;
//cert.X509Extensions.Add((CX509Extension)eku); // add the EKU
cert.HashAlgorithm = hashobj; // Specify the hashing algorithm
cert.Encode(); // encode the certificate
// Do the final enrollment process
var enroll = new CX509Enrollment();
enroll.InitializeFromRequest(cert); // load the certificate
enroll.CertificateFriendlyName = subjectName; // Optional: add a friendly name
string csr = enroll.CreateRequest(); // Output the request in base64
// and install it back as the response
enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate,
csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); // no password
// output a base64 encoded PKCS#12 so we can import it back to the .Net security classes
var base64encoded = enroll.CreatePFX("", // no password, this is for internal consumption
PFXExportOptions.PFXExportChainWithRoot);
// instantiate the target class with the PKCS#12 data (and the empty password)
return new System.Security.Cryptography.X509Certificates.X509Certificate2(
System.Convert.FromBase64String(base64encoded), "",
// mark the private key as exportable (this is usually what you want to do)
// mark private key to go into the Machine store instead of the current users store
X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet
);
}
我用這個代碼存儲它:
X509Store store = new X509Store(storeName, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadWrite);
store.Add(newCert);
store.Close();
這將創建證書並將其放入 LocalMachine 證書存儲區。 問題是,當我嘗試啟動 WCF 服務時,出現以下異常:
證書“CN=myCertificate”可能沒有能夠進行密鑰交換的私鑰,或者進程可能沒有私鑰的訪問權限。 詳情請參閱內部異常。 內部異常:密鑰集不存在
我的證書的 FindPrivateKey 示例 ( http://msdn.microsoft.com/en-us/library/aa717039%28v=vs.100%29.aspx ) 的輸出是:
Private key directory:
C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys
Private key file name:
f0d47c7826b8ef5148b6d412f1c40024_4a8a026f-58e4-40f7-b779-3ae9b6aae1a7
我可以在資源管理器中看到這個 1.43KB 的文件。 如果我查看屬性|安全性,我會看到 SYSTEM 和 Administrators 都具有完全控制權。
在研究這個錯誤時,我看到了很多關於私鑰丟失或權限不正確的答案。 我看不出是什么問題。
真正奇怪的是,如果我使用 mmc 證書插件,轉到證書並選擇所有任務|管理私鑰...我看到相同的安全設置。 查看此內容后,即使我只是打開對話框並點擊取消按鈕,證書現在也可以在 WCF 中正常工作。 我可以簡單地重新啟動服務,一切運行完美。
如果我使用 MakeCert 創建證書,它從一開始就可以正常工作。 我不知道它的作用有什么不同。
另一條可能不相關的信息是,證書不僅會放在我告訴它放在的“我的商店”中,而且還會放在“中間證書頒發機構”商店中。 我不知道為什么或者這是否重要。
所以......任何想法我做錯了什么?
更新:嗯,這不僅僅是 WCF 問題。 當我嘗試使用證書綁定到帶有 http.sys 的端點時,我基本上遇到了同樣的問題,使用HttpSetServiceConfiguration 。 該方法返回 1312 -“指定的登錄會話不存在。它可能已被終止”。 這實際上並不是真正的錯誤。 我在安全事件日志中看到了一個審計失敗,它說:
Cryptographic Parameters:
Provider Name: Microsoft Software Key Storage Provider
Algorithm Name: Not Available.
Key Name: {A23712D0-9A7B-4377-89DB-B1B39E3DA8B5}
Key Type: Machine key.
Cryptographic Operation:
Operation: Open Key.
Return Code: 0x80090011
0x80090011 是找不到對象。 所以這似乎是同樣的問題。 同樣,在我打開證書的“管理私鑰”對話框后,這也完美無缺。
我仍在尋找問題的原因。
更新#2:我能夠使用下面接受的答案來完成這項工作。 有趣的是,這段代碼現在似乎沒有調用 X509Store 代碼就將證書放在 Machine 存儲中。 我仍然調用代碼,因為我不確定並且它不會傷害任何東西。 這是我用來創建證書的最終代碼。
static public X509Certificate2 CreateSelfSignedCertificate(string subjectName, TimeSpan expirationLength)
{
// create DN for subject and issuer
var dn = new CX500DistinguishedName();
dn.Encode("CN=" + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE);
CX509PrivateKey privateKey = new CX509PrivateKey();
privateKey.ProviderName = "Microsoft Strong Cryptographic Provider";
privateKey.Length = 2048;
privateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE;
privateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_DECRYPT_FLAG | X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_KEY_AGREEMENT_FLAG;
privateKey.MachineContext = true;
privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG;
privateKey.Create();
// Use the stronger SHA512 hashing algorithm
var hashobj = new CObjectId();
hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID,
ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY,
AlgorithmFlags.AlgorithmFlagsNone, "SHA512");
// Create the self signing request
var cert = new CX509CertificateRequestCertificate();
cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, "");
cert.Subject = dn;
cert.Issuer = dn; // the issuer and the subject are the same
cert.NotBefore = DateTime.Now.Date;
// this cert expires immediately. Change to whatever makes sense for you
cert.NotAfter = cert.NotBefore + expirationLength;
cert.HashAlgorithm = hashobj; // Specify the hashing algorithm
cert.Encode(); // encode the certificate
// Do the final enrollment process
var enroll = new CX509Enrollment();
enroll.InitializeFromRequest(cert); // load the certificate
enroll.CertificateFriendlyName = subjectName; // Optional: add a friendly name
string csr = enroll.CreateRequest(); // Output the request in base64
// and install it back as the response
enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate,
csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); // no password
// output a base64 encoded PKCS#12 so we can import it back to the .Net security classes
var base64encoded = enroll.CreatePFX("", // no password, this is for internal consumption
PFXExportOptions.PFXExportChainWithRoot);
// instantiate the target class with the PKCS#12 data (and the empty password)
return new System.Security.Cryptography.X509Certificates.X509Certificate2(
System.Convert.FromBase64String(base64encoded), "",
// mark the private key as exportable (this is usually what you want to do)
// mark private key to go into the Machine store instead of the current users store
X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet
);
}
我無法完成這項工作,但我找到了替代解決方案。 (2014 年 12 月更新:我現在已經使用接受的答案讓它工作了。)
我能夠使用PluralSight.Crypto 庫來實現我所需要的。 我不得不稍微修改源代碼以獲取要存儲在 LocalMachine 存儲中的私鑰。 我所做的更改是對文件 CryptContext.cs 進行的。 我更改了 CreateSelfSignedCertificate 方法。 以下是一段代碼,包括我所做的更改。 本質上,如果 CryptContext 對象在其標志中包含此值,我將 CryptKeyProviderInformation 結構的標志成員設置為 0x20 (CRYPT_MACHINE_KEYSET)。
byte[] asnName = properties.Name.RawData;
GCHandle asnNameHandle = GCHandle.Alloc(asnName, GCHandleType.Pinned);
int flags = 0; // New code
if ((this.Flags & 0x20) == 0x20) // New code
flags = 0x20; // New code
var kpi = new Win32Native.CryptKeyProviderInformation
{
ContainerName = this.ContainerName,
KeySpec = (int)KeyType.Exchange,
ProviderType = 1, // default RSA Full provider
Flags = flags // New code
};
然后我在自己的代碼中使用該函數,如下所示:
using (Pluralsight.Crypto.CryptContext ctx = new Pluralsight.Crypto.CryptContext()) {
ctx.Flags = 0x8 | 0x20;
ctx.Open();
X509Certificate2 cert = ctx.CreateSelfSignedCertificate(
new Pluralsight.Crypto.SelfSignedCertProperties
{
IsPrivateKeyExportable = true,
KeyBitLength = 4096,
Name = new X500DistinguishedName("CN=" + subjectName),
ValidFrom = DateTime.Today,
ValidTo = DateTime.Today + expirationLength,
});
return cert;
}
請注意,我將 CryptContext 對象的標志設置為 0x8 | 0x20 (CRYPT_NEWKEYSET | CRYPT_MACHINE_KEYSET)。
我希望我能弄清楚我原來的解決方案有什么問題。 但是我需要一些東西來工作,在我的測試中,這個解決方案可以滿足我的需求。 我希望它可以幫助其他人。
我在 PowerShell 中使用等效代碼時遇到了同樣的問題。 似乎有時私鑰會消失。 我使用了 Process Monitor,您可以看到正在刪除的密鑰文件。
我解決這個問題的方法是將X509KeyStorageFlags.PersistKeySet
添加到 X509Certificate2 構造函數。
您還可以在 CodePlex ( https://clrsecurity.codeplex.com/ ) 上使用 CLR 安全庫。 這是創建自簽名證書並使用 SSLStream 對其進行測試的示例代碼。
var machineName = Environment.MachineName;
var keyCreationParameters = new CngKeyCreationParameters();
keyCreationParameters.KeyUsage = CngKeyUsages.AllUsages;
keyCreationParameters.KeyCreationOptions = CngKeyCreationOptions.OverwriteExistingKey;
keyCreationParameters.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(4096), CngPropertyOptions.None));
var cngKey = CngKey.Create(CngAlgorithm2.Rsa, "Test", keyCreationParameters);
var x500DistinguishedName = new X500DistinguishedName("CN=" + machineName);
x500DistinguishedName.Oid.Value = "1.3.6.1.5.5.7.3.1";
var certificateCreationParameters = new X509CertificateCreationParameters(x500DistinguishedName);
certificateCreationParameters.SignatureAlgorithm = X509CertificateSignatureAlgorithm.RsaSha512;
certificateCreationParameters.TakeOwnershipOfKey = true;
certificateCreationParameters.CertificateCreationOptions = X509CertificateCreationOptions.None;
certificateCreationParameters.EndTime = new DateTime(9999, 12,31, 23, 59, 59, 999, DateTimeKind.Utc);
var certificate = cngKey.CreateSelfSignedCertificate(certificateCreationParameters);
var certificateStore = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
certificateStore.Open(OpenFlags.ReadWrite);
certificateStore.Add(certificate);
certificateStore.Close();
var tcpListener = TcpListener.Create(6666);
tcpListener.Start();
var client = new TcpClient("localhost", 6666);
var acceptedClient = tcpListener.AcceptTcpClient();
var acceptedClinetSslStream = new SslStream(
acceptedClient.GetStream(), false);
var serverAuthTask = acceptedClinetSslStream.AuthenticateAsServerAsync(certificate,
false, SslProtocols.Tls, true);
SslStream clientSslStream = new SslStream(
client.GetStream(),
false,
delegate(object o, X509Certificate x509Certificate, X509Chain chain, SslPolicyErrors errors)
{
if (errors == SslPolicyErrors.None)
return true;
Console.WriteLine("Certificate error: {0}", errors);
// Do not allow this client to communicate with unauthenticated servers.
return false;
},
null);
var clientAuthTask = clientSslStream.AuthenticateAsClientAsync(machineName);
Task.WaitAll(serverAuthTask, clientAuthTask);
@Paul,我找不到X509CertificateCreationParameters的庫。 猜猜哪里有嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.