OpenSSL证书缺少私钥C#

时间:2020-10-21 11:53:31

标签: c# .net-core openssl

我得到一个代码:

        string certificateText = File.ReadAllText("./Certificates/cert.pem");
        string privateKeyText = File.ReadAllText("./Certificates/key.pem");
        var provider = new CertificateFromFileProvider(certificateText, privateKeyText);
        certificate = provider.Certificate;

当我检查私钥字段时,得到空值。此外,privateKeyText也具有价值。 enter image description here

1 个答案:

答案 0 :(得分:0)

已通过生成p12证书解决

openssl pkcs12 -export -in cert.pem -inkey "privateKey.pem" -out myProject_keyAndCertBundle.p12

然后更改了我的代码

    public static string userId = "6L29##############################SfkI";
    public static string password = "87t##########GLV";

    public static string cert = "./Certificates/myProject_keyAndCertBundle.p12";
    public static string certificatePassword= "####Password#######";


 HttpWebRequest request = WebRequest.Create(requestURL) as HttpWebRequest;
        request.ContentType = "application/json";
        request.Accept = "application/json";

        request.Method = method;
        if (method.Equals("POST") || method.Equals("PUT"))
        {
            // Load the body for the post request
            var requestStringBytes = Encoding.UTF8.GetBytes(requestBodyString);
            request.GetRequestStream().Write(requestStringBytes, 0, requestStringBytes.Length);
        }

        if (headers != null)
        {
            foreach (KeyValuePair<string, string> header in headers)
            {
                request.Headers[header.Key] = header.Value;
            }
        }

        // Add headers
        request.Headers["Authorization"] = GetBasicAuthHeader(userId, password);

        // Add certificate
        var certificate = new X509Certificate2(certificatePath, certificatePassword);
        request.ClientCertificates.Add(certificate);

        try
        {
            // Make the call
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                LogResponse(testInfo, response);
                statusCode = response.StatusCode.ToString();
            }
        }
        catch (WebException e)
        {
            if (e.Response is HttpWebResponse)
            {
                HttpWebResponse response = (HttpWebResponse)e.Response;
                LogResponse(testInfo, response);
                statusCode = response.StatusCode.ToString();
            }
        }
        return statusCode;
    }