I have to send an xml payload to a client Webservice. The client provided me the URL, the certificate and public key. The certificate & public key file are in a .der file. I'm writing a Command Line Application in C# to do the task. I greatly appreciate if someone could point me the right direction how to sign the certificate with the provide public key in the der file.
What I have tried:
Here is the sample code I wrote so far.
public string postXMLData(string destinationUrl, string requestXml)
{
Constants.Logger.InfoFormat(@"Posting XMLData To URL : {0}", destinationUrl);
string responseStr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;
Stream requestStream = null;
try
{
X509Certificate cert = X509Certificate.CreateFromCertFile(String.Format(@"{0}\{1}", DEFAULT_CERT_LOCATION, CERTIFATE_FILE_NAME));
request = (HttpWebRequest)WebRequest.Create(destinationUrl);
byte[] bytes;
bytes = System.Text.Encoding.UTF8.GetBytes(requestXml);
request.ContentType = "application/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
request.KeepAlive = false;
request.UserAgent = null;
request.Timeout = 99999;
request.ReadWriteTimeout = 99999;
request.ServicePoint.MaxIdleTime = 99999;
request.ClientCertificates.Add(cert);
System.Net.ServicePointManager.CertificatePolicy =
new TrustAllCertificatePolicy();
Constants.Logger.InfoFormat(@"Getting Request Stream.....");
requestStream = request.GetRequestStream();
Constants.Logger.InfoFormat(@"Writing To Request Stream.....");
requestStream.Write(bytes, 0, bytes.Length);
Constants.Logger.InfoFormat(@"Writing To Request Stream.....Done.");
requestStream.Close();
Constants.Logger.InfoFormat(@"Closing Request Stream.....Done.");
Constants.Logger.InfoFormat(@"Waiting For Response.....");
response = (HttpWebResponse)request.GetResponse();
Constants.Logger.InfoFormat(@"Response Code : {0}", response.StatusCode);
using (Stream responseStream = response.GetResponseStream())
{
responseStr = new StreamReader(responseStream).ReadToEnd();
}
Constants.Logger.InfoFormat(@"Response Data : ", responseStr);
}
catch (Exception ex)
{
Constants.Logger.ErrorFormat(@"Error Posting data to the stream : {0}", ex);
}
finally
{
if (response != null)
{
response.Close();
}
if(requestStream != null)
{
requestStream.Close();
}
}
return responseStr;
}
public class TrustAllCertificatePolicy : System.Net.ICertificatePolicy
{
public TrustAllCertificatePolicy()
{ }
public bool CheckValidationResult(ServicePoint sp,
System.Security.Cryptography.X509Certificates.
X509Certificate cert, WebRequest req, int problem)
{
return true;
}
}