I'm writing a client/server application that requires the server needs to be able to authenticate the client and also requires all comms to be encrypted. 

The mechanism to provide this needs to be self contained within the server and client application and also to be fully automated (no human interaction required). SSL seems to be the best way to do this and is also something I am familiar with using. 

For each client that needs the client software deploying to it, I planned to create (on the fly) an MSI installer with the application, the clients certificate (signed by the server) and private key and the servers public certificate (so the clients can authenticate the server - the server certificate could be self signed). 

I can generate the key for the client and make a CSR, but don't seem to be able to find a way of actually signing the CSR and generating a certificate for the client thou. I have looked into the Win32 Crypto API, but haven't managed to find any examples of how to actually sign a CSR and get a client certificate.

I know how to do all of this from the command line with the openssl tool, but am not sure of how to do it from within an application.

Please note that making system calls out to the openssl tool and passing in the parameters I know to work is not an option as it's a huge security risk to rely on the openssl tool not being compromised in any way. Doing it this way wouldn't for fill the self contained requirement.

I am going about this the right way, or is there a better way to achieve the same thing - basically authentication of the clients connecting to the server and a way of the connecting client to authenticate the server they connect to, all encrypted.

I cannot make any assumptions about the server (or clients) having a static IP or hostname (DNS can be broken anyways), nor can I make any assumptions about any existing PKI infrastructure.

I am writing this primarily in C#.Net, but would consider writing a C++ extension to this if it gives me this functionality.

Finally this is my first post here, so if I've missed out something obvious or have been short on any details, please ask and I'll fill in the gaps :)

Thanks,

James