最终为此制定了解决方案。不理想,但它有效。基本上,它使用 bouncyCastle 创建一个 pfx 流,然后您可以将其读入以加载带有证书的私钥。为此,我在 CoreCLR 上使用了 nuget 包 Portable.BouncyCastle:1.8.1,并将以下代码放入了帮助程序类中。
public X509Certificate2 CreateX509Certificate2(RSAParameters keys, byte[] certificateBytes, string friendlyName)
{
if (string.IsNullOrWhiteSpace(friendlyName))
{
friendlyName = "default";
}
var store = new Pkcs12Store();
var convertedKeys = GetRsaKeyPair(keys);
var certificate = new X509CertificateParser().ReadCertificate(certificateBytes);
store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(convertedKeys.Private), new X509CertificateEntry[] { new X509CertificateEntry(certificate)});
using (MemoryStream ms = new MemoryStream())
{
var random = new SecureRandom();
string password = random.Next().ToString() + random.Next().ToString() + random.Next().ToString();
store.Save(ms, password.ToCharArray(), random);
var cert = new X509Certificate2(ms.ToArray(), password, X509KeyStorageFlags.Exportable);
return cert;
}
}
private AsymmetricCipherKeyPair GetRsaKeyPair(
RSAParameters rp)
{
BigInteger modulus = new BigInteger(1, rp.Modulus);
BigInteger pubExp = new BigInteger(1, rp.Exponent);
RsaKeyParameters pubKey = new RsaKeyParameters(
false,
modulus,
pubExp);
RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters(
modulus,
pubExp,
new BigInteger(1, rp.D),
new BigInteger(1, rp.P),
new BigInteger(1, rp.Q),
new BigInteger(1, rp.DP),
new BigInteger(1, rp.DQ),
new BigInteger(1, rp.InverseQ));
return new AsymmetricCipherKeyPair(pubKey, privKey);
}