Archived Forum Post

Index of archived forum posts

Question:

How to use a client-side certificate and private key for an SSL/TLS connection?

Jul 26 '12 at 17:05

I am trying to make an SSL connection to the remote server.

I can verify remote Certificate after connection. But the remote server also need to check the client certificate after connection.

I have created a .pem file also a private key file which also a .pem file. How can I load my certificate and my private key before connection to the server.

I tried the following code but I don’t know how to load my private key

CkSocket socket;
CkCert ckClientCert;
ckClientCert.LoadFromFile("myclientCertfile.pem");
socket.SetSslClientCert(ckClientCert);   
success = socket.Connect(sslServerHost,sslServerPort,ssl,maxWaitMillisec);

Answer

Before answering the question, there are a few issues with the code snippet above. The return value (usually a boolean success/failure status) of any Chilkat method call that has the possibility of failing should be checked. Therefore, make sure to check the success of the LoadFromFile and SetSslClentCert method calls prior to proceeding. If a method call fails, get more information via the LastErrorText property.

To load a cert + private key from PEM, combine both PEM's into a single PEM file, and then call SetSslClientCertPem. The method signature for SetSslClientCertPem looks like this:

public bool SetSslClientCertPem(string pemDataOrFilename, string pemPassword);

PEM files are human-readable text files that may be edited in any text editor. The certificate and private key data are encoded using Base64, which is an encoding similar to Hex encoding such that binary data is represented by printable us-ascii chars.

The PEM for a certificate will look like this:

-----BEGIN CERTIFICATE-----
MIIBqTCCAWOgAwIBAgIBCDANBgkqhkiG9w0BAQUFADBZMQswCQYDVQQGEwJOTDES
MBAGA1UECBMJQW1zdGVyZGFtMRIwEAYDVQQHEwlBbXN0ZXJkYW0xEDAOBgNVBAoT
B2tsbS5jb20xEDAOBgNVBAMTB1Jvb3QgQ0EwHhcNOTkxMDA0MTMxNzIyWhcNMjkw
...
ADAYBgNVHREEETAPggJldoIJbG9jYWxob3N0MA0GCSqGSIb3DQEBBQUAAzEAF0zP
Z+KB1CwqTd1dXtjnsoPvXQOmM/zf98rofJ9YQ/Xq3T+wJo17kxBmE6Y+xh7+
-----END CERTIFICATE-----

The PEM for a private key will look something like this:

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,BB85CF01A0D2D218

fvXb+oHJK+Z79mEwEHHdriETMtQdElMTn6QLQbsBVdzGfbhVbrSsdfSw1Ooi7lXo
MNASw9PXa0bc0Orpm8Kp2BvC5cMh5GGzvfNQF3RIUknwENo2WeFBDOs7Yotg2p0P
...
x9tAn7ug1dJ0eforu7/v8yTSLFD7iawwHB5X7ha1D85k7tVQUQPx7ovkqM2RkL0o
2D4vjpFBIAGW6dbT4ESBuX75Q7dd5qROCfG/T0wm8cY2TXPOs4Kq02pnEUL2KOfB
pu0hHAxTh1I=
-----END RSA PRIVATE KEY-----

You may create a PEM file that contains the cert, private key, and any additional certificates in the chain of authentication. Simply create a text file and cut-and-paste each PEM, one following the other, and save it. Then use this file w/ the SetSslClientCertPem method.