具有相互认证的WebRequest

时间:2019-04-10 10:06:41

标签: ssl x509certificate

在Crypt32发表评论后附加其他信息(谢谢Crypt32!)

我必须将数据发送到服务器。我需要相互身份验证:服务器需要确定它是我,并且我需要确定服务器确实是我信任的服务器。这需要在Windows程序中使用。

为了标识自己,服务器将向我发送由我信任的证书颁发机构颁发的证书:根证书和中间证书:

  • 根CA-G2.PEM
  • 中间CA-G2.PEM

为识别我的身份,该组织给了我一个证书和一个私钥

  • 根CA-G3.PEM
  • 中间CA-G3.PEM
  • MyCertificate.CRT(= pem)和MyCertificate.Private.Key(= RSA)

我已将所有根证书和中间证书导入Windows密钥库。

发送消息:

const string url = "https://...//Deliver";
HttpWebRequest webRequest = WebRequest.CreateHttp(url);

// Security:
webRequest.AuthenticationLevel=AuthenticationLevel.MutualAuthRequired;
webRequest.Credentials = CredentialCache.DefaultCredentials;

// Should I add my certificate?
X509Certificate myCertificate = new X509Certificate("MyCertificate.CRT");

// Should I add Certificate authorities?
// only the CA-G2 authorities, so my WebRequest can trust the certificate
// that will be sent by the Server?
// or Should I also add the CA-G3 who issued MyCertificate

// and what about MyCertificate.Private.Key, the RSA file?

// Fill the rest of the WebRequest:
webRequest.Method = "Post";
webRequest.Accept = "text/xml";
webRequest.Headers.Add("SOAP:Action");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
... etc

// do the call and display the result
using (WebResponse response = webRequest.GetResponse())
{
    using (var reader = new StreamReader(response.GetResponseStream()))
    {
        string soapResult = reader.ReadToEnd();
        Console.WriteLine(soapResult);
    }
}

WebResponse不指示任何错误。返回的数据是一个空(非空)字符串。但是:

response.StatusCode == NoContent (204)
soapResult == String.Empty
response.IsMutuallyAuthenticated == false

期望NoContent和空数据结果。错误的IsMutuallyAuthenticated是否表示我的身份验证有问题?

添加的信息

Crypt32建议我将MyCertificate.CRT和MyCertificate.Private.Key转换为一个PFX(或P12)文件。

为此,我使用openssl。

我将CA-G3文件串联到一个TrustG3.Pem中,并创建了P12文件:

openssl.exe pkcs12 -export -name "<some friendly name>"
                   -certfile TrustG3.Pem
                   -in MyCertificate.CRT
                   -inkey MyCertificate.Private.Key
                   -out MyCertificate.P12

提供密码后,创建了正确的Pkcs12文件(PFX)。源代码略有变化:

HttpWebRequest webRequest = WebRequest.CreateHttp(url);

// Security:
webRequest.AuthenticationLevel=AuthenticationLevel.MutualAuthRequired;
webRequest.Credentials = CredentialCache.DefaultCredentials;
var p12Certificate = new X509Certificate("MyCertificate.P12", "my password");
webRequest.ClientCertificates.Add(p12Certificate);

A,这没有帮助。 webResponse仍然显示:

response.IsMutuallyAuthenticated == false

1 个答案:

答案 0 :(得分:0)

  

错误的IsMutuallyAuthenticated是否表示我的身份验证有问题?

是的,确实如此。因为您仅添加了客户端证书的公共部分。没有指定关联的私钥。可以使用证书存储中的证书(假设证书存储中包含私钥),也可以使用PFX导入证书。

更新

现在您的客户端身份验证代码看起来正确。下一步是检查服务器是否信任您的客户端证书。