2 回答

TA貢獻1821條經驗 獲得超6個贊
您要求的有幾件不同的事情,而且容易程度各不相同。
將私鑰附加到證書
從 .NET Framework 4.7.2 或 .NET Core 2.0 開始,您可以組合證書和密鑰。它不修改證書對象,而是生成一個知道密鑰的新證書對象。
using (X509Certificate2 pubOnly = new X509Certificate2("myCert.crt"))
using (X509Certificate2 pubPrivEphemeral = pubOnly.CopyWithPrivateKey(privateKey))
{
// Export as PFX and re-import if you want "normal PFX private key lifetime"
// (this step is currently required for SslStream, but not for most other things
// using certificates)
return new X509Certificate2(pubPrivEphemeral.Export(X509ContentType.Pfx));
}
在 .NET Framework(但不是 .NET Core)上,如果您的私鑰是RSACryptoServiceProvider或者DSACryptoServiceProvider您可以使用cert.PrivateKey = key,但是這有復雜的副作用并且不鼓勵。
加載私鑰
這個比較難,除非你已經解決了。
大多數情況下,答案是在不使用 BouncyCastle 的情況下使用 c# 中的數字簽名,但如果您可以遷移到 .NET Core 3.0,事情就會變得容易得多。
PKCS#8 私鑰信息
從 .NET Core 3.0 開始,您可以相對簡單地執行此操作:
using (RSA rsa = RSA.Create())
{
rsa.ImportPkcs8PrivateKey(binaryEncoding, out _);
// do stuff with the key now
}
(當然,如果您有 PEM,則需要通過提取 BEGIN 和 END 定界符之間的內容并運行它Convert.FromBase64String以獲取來“去 PEM”它binaryEncoding)。
PKCS#8 加密私鑰信息
從 .NET Core 3.0 開始,您可以相對簡單地執行此操作:
using (RSA rsa = RSA.Create())
{
rsa.ImportEncryptedPkcs8PrivateKey(password, binaryEncoding, out _);
// do stuff with the key now
}
(如上所述,如果它是 PEM,您需要先“去 PEM”)。
PKCS#1 RSAPprivateKey
從 .NET Core 3.0 開始,您可以相對簡單地執行此操作:
using (RSA rsa = RSA.Create())
{
rsa.ImportRSAPrivateKey(binaryEncoding, out _);
// do stuff with the key now
}
(如果是 PEM,則為相同的“de-PEM”)。

TA貢獻2065條經驗 獲得超14個贊
最后我這樣做了,效果很好:
...
if (!File.Exists(pfx)) {
// Generate PFX
string arguments = "openssl pkcs12 -export -in " + certPath + "" + certFile + ".crt -inkey " + certPath + "" + certFile + ".key -out " + certPath + "" + certFile + ".pfx -passout pass:" + pfxPassword;
ProcessStartInfo opensslPsi = new ProcessStartInfo("sudo", arguments);
opensslPsi.UseShellExecute = false;
opensslPsi.RedirectStandardOutput = true;
using (Process p = Process.Start(opensslPsi)) {
p.WaitForExit();
}
// Set Permission
ProcessStartInfo chmodPsi = new ProcessStartInfo("sudo", "chmod 644 " + certPath + "" + certFile + ".pfx");
chmodPsi.UseShellExecute = false;
chmodPsi.RedirectStandardOutput = true;
using (Process p = Process.Start(chmodPsi)) {
p.WaitForExit();
}
}
sslCertificate = new X509Certificate2(pfx, pfxPassword);
...
- 2 回答
- 0 關注
- 340 瀏覽
添加回答
舉報