X509Certificate2 的 .pem 私钥
.pem private key to X509Certificate2
我有一个 .pem 作为私钥:
-----BEGIN RSA PRIVATE KEY-----
KEY
-----END RSA PRIVATE KEY-----
当我尝试转换为 X509Certificate2 时出现以下错误:
Cannot find the requested object.
我尝试过的:
static byte[] PEM(string type, byte[] data)
{
string pem = Encoding.ASCII.GetString(data);
string header = String.Format("-----BEGIN {0}-----", type);
string footer = String.Format("-----END {0}-----", type);
int start = pem.IndexOf(header) + header.Length;
int end = pem.IndexOf(footer, start);
string base64 = pem.Substring(start, (end - start));
return Convert.FromBase64String(base64);
}
static X509Certificate2 LoadCertificateFile(string filename)
{
X509Certificate2 x509 = null;
using (FileStream fs = System.IO.File.OpenRead(filename))
{
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
if (data[0] != 0x30)
{
data = PEM("RSA PRIVATE KEY", data);
}
if (data != null)
x509 = new X509Certificate2(data); //Here i get the error
}
return x509;
}
client_pk = LoadCertificateFile(@"..\private.pem");
我可以从 .PFX 文件导入完整 证书。我认为您可以使用 OpenSSL 将 .PEM 转换为 .PFX。这是为我工作的 .PFX 文件加载代码:
SecureString secStr = new SecureString();
"<your_password>".ToCharArray().ToList().ForEach(c => secStr.AppendChar(c));
var cert = new X509Certificate2();
cert.Import("<your path to .PFX file>", secStr, X509KeyStorageFlags.Exportable);
我有一个 .pem 作为私钥:
-----BEGIN RSA PRIVATE KEY-----
KEY
-----END RSA PRIVATE KEY-----
当我尝试转换为 X509Certificate2 时出现以下错误:
Cannot find the requested object.
我尝试过的:
static byte[] PEM(string type, byte[] data)
{
string pem = Encoding.ASCII.GetString(data);
string header = String.Format("-----BEGIN {0}-----", type);
string footer = String.Format("-----END {0}-----", type);
int start = pem.IndexOf(header) + header.Length;
int end = pem.IndexOf(footer, start);
string base64 = pem.Substring(start, (end - start));
return Convert.FromBase64String(base64);
}
static X509Certificate2 LoadCertificateFile(string filename)
{
X509Certificate2 x509 = null;
using (FileStream fs = System.IO.File.OpenRead(filename))
{
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
if (data[0] != 0x30)
{
data = PEM("RSA PRIVATE KEY", data);
}
if (data != null)
x509 = new X509Certificate2(data); //Here i get the error
}
return x509;
}
client_pk = LoadCertificateFile(@"..\private.pem");
我可以从 .PFX 文件导入完整 证书。我认为您可以使用 OpenSSL 将 .PEM 转换为 .PFX。这是为我工作的 .PFX 文件加载代码:
SecureString secStr = new SecureString();
"<your_password>".ToCharArray().ToList().ForEach(c => secStr.AppendChar(c));
var cert = new X509Certificate2();
cert.Import("<your path to .PFX file>", secStr, X509KeyStorageFlags.Exportable);