Click here to Skip to main content
Licence CPOL
First Posted 6 Aug 2008
Views 22,600
Downloads 315
Bookmarked 36 times

Attaching a digital certificate (public key) to an HTTPS request

By | 6 Aug 2008 | Article
Posting data to HTTPS (a secure connection) URL from a Windows application (.NET) by attaching a digital certificate and getting the response back.

Introduction

This article will guide you on how to post data to an HTTPS (i.e., secure connection) URL from a Windows application (.NET) by attaching a digital certificate from a certificate file and getting the response back. The code is written in C#.

Background

No special background knowledge is needed for this article. Any beginner or intermediate programmer will be able to understand this code.

Using the Code

You should have a valid certificate file which you will use to post data to a secure website/web service by attaching that certificate. Actually, by this, you are going to attach a public key to your HTTPS request. Another way is to go through all the certificates which are installed in your PC and get the right one from the store list and then attach the public key to your HTTPS request. You can use either method. But here, I am going to use the first method.

//
private void postFile()
{
   HttpWebRequest req = null;
   HttpWebResponse rsp = null;
  
   X509Certificate cert = X509Certificate.CreateFromCertFile("d:\\cert\\abc.crt");
   // Create a  X509Certificat object from yor certificate.
   // other way is to go through all the cerificates  which are installed
   // in your Pc and get the right one from the store list

   string uri = "https://abc.com:2111/test.aspx"; 

   // A url which is looking for the right public key with 
   // the incomming https request

    String myfile = File.ReadAllText("C:\\somfile.xml");

    req = (HttpWebRequest)System.Net.WebRequest.Create(uri);

    String DataToPost = this.GetTextFromXMLFile(myfile);
   
    String strSenderID = "123";

    req.Method = "POST";        // Post method
    req.ContentType = "application/octet-stream";   // content type
    //You can also use ContentType = "text/xml";
   
    req.Headers.Add("sender-id", strSenderID);  
   // Some Header information which you would like to send 
   // with the request
    req.ContentLength = 1000; 
    req.KeepAlive = false;
    req.UserAgent = null;
    req.Timeout = 99999;
    req.ReadWriteTimeout = 99999;
    req.ServicePoint.MaxIdleTime = 99999;

    req.ClientCertificates.Add(cert);
    // Attaching the Certificate To the request

    System.Net.ServicePointManager.CertificatePolicy = 
                           new TrustAllCertificatePolicy();

    // when you browse manually you get a dialogue box asking 
    // that whether you want to browse over a secure connection.
    // this line will suppress that message
    //(pragramatically saying ok to that message). 

    StreamWriter writer = new StreamWriter(req.GetRequestStream());

    writer.WriteLine(this.GetTextFromXMLFile(myfile));

    writer.Close();

    rsp = (HttpWebResponse)req.GetResponse();

    System.IO.StreamReader reader = 
           new System.IO.StreamReader(rsp.GetResponseStream());
    String retData = reader.ReadToEnd();

    if (req != null) req.GetRequestStream().Close();
    if (rsp != null) rsp.GetResponseStream().Close();
  
}

This function will read the contents of the file and return back the file contents.

//
private string GetTextFromXMLFile(string file)  // this 
{
    StreamReader reader = new StreamReader(file);
    string ret = reader.ReadToEnd();
    reader.Close();
    return ret;
}//

The function TrustAllCertificatePolicy() will catch a certificate policy exception for a custom certificate policy.

//
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;
    }
}
//

Points of Interest

Cryptography is really a big area of study, and here we have just discussed a small part of it. I will soon be updating this article with the latest source code.

Check out my other article here: Using Crystal Reports with Oracle and Parametrized Query (Passing SQL query parameters to Crystal Reports).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Rehan Ahmad Abbasi

Software Developer (Senior)
Al-Jazirah Corporation Riyadh KSA
United Arab Emirates United Arab Emirates

Member

I am a Software Engineer having 4 + years of experience in various skill sets.
Proficiency in Asp.net, C#.net, Vb.net, Ado.net, VB 6.0, J2ME, Ajax, Xslt, Xml, Smart Device (Pocket PC 2003), and Oracle.
 
Extensive experience with analyzing, designing, development, and maintenance of Internet, Intranet, Client Server and Object Oriented applications built on .NET Framework (windows and web app.) and VB 6.0.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Questionvery good thanks! Pinmemberasusronaldo0:10 1 Feb '12  
GeneralMy vote of 1 Pinmemberjohn_17266:19 18 Jan '10  
GeneralThanks Pinmembersumovn20:03 2 May '09  
GeneralPlease Vote for this article PinmemberRehan Ahmad Abbasi5:25 24 Aug '08  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 6 Aug 2008
Article Copyright 2008 by Rehan Ahmad Abbasi
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid