2 回答

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超6個(gè)贊
您要求的有幾件不同的事情,而且容易程度各不相同。
將私鑰附加到證書(shū)
從 .NET Framework 4.7.2 或 .NET Core 2.0 開(kāi)始,您可以組合證書(shū)和密鑰。它不修改證書(shū)對(duì)象,而是生成一個(gè)知道密鑰的新證書(shū)對(duì)象。
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,但是這有復(fù)雜的副作用并且不鼓勵(lì)。
加載私鑰
這個(gè)比較難,除非你已經(jīng)解決了。
大多數(shù)情況下,答案是在不使用 BouncyCastle 的情況下使用 c# 中的數(shù)字簽名,但如果您可以遷移到 .NET Core 3.0,事情就會(huì)變得容易得多。
PKCS#8 私鑰信息
從 .NET Core 3.0 開(kāi)始,您可以相對(duì)簡(jiǎn)單地執(zhí)行此操作:
using (RSA rsa = RSA.Create())
{
rsa.ImportPkcs8PrivateKey(binaryEncoding, out _);
// do stuff with the key now
}
(當(dāng)然,如果您有 PEM,則需要通過(guò)提取 BEGIN 和 END 定界符之間的內(nèi)容并運(yùn)行它Convert.FromBase64String以獲取來(lái)“去 PEM”它binaryEncoding)。
PKCS#8 加密私鑰信息
從 .NET Core 3.0 開(kāi)始,您可以相對(duì)簡(jiǎn)單地執(zhí)行此操作:
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 開(kāi)始,您可以相對(duì)簡(jiǎn)單地執(zhí)行此操作:
using (RSA rsa = RSA.Create())
{
rsa.ImportRSAPrivateKey(binaryEncoding, out _);
// do stuff with the key now
}
(如果是 PEM,則為相同的“de-PEM”)。

TA貢獻(xiàn)2065條經(jīng)驗(yàn) 獲得超14個(gè)贊
最后我這樣做了,效果很好:
...
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 關(guān)注
- 352 瀏覽
添加回答
舉報(bào)