Sample code for 30+ languages & platforms
C

SFTP Authentication using an SSH Certificate

See more SFTP Examples

Demonstrates how to SFTP authenticate using an SSH certificate.

Chilkat C Downloads

C
#include <C_CkStringBuilder.h>
#include <C_CkSshKey.h>
#include <C_CkSFtp.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkStringBuilder sbSshCert;
    HCkStringBuilder sbPrivKey;
    HCkSshKey key;
    HCkSFtp sftp;
    const char *hostname;
    int port;

    success = FALSE;

    // This example assumes the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    sbSshCert = CkStringBuilder_Create();
    success = CkStringBuilder_LoadFile(sbSshCert,"qa_data/sshCert/user_ecdsa_key-cert.pub","utf-8");
    if (success == FALSE) {
        printf("Failed to load user_ecdsa_key-cert.pub\n");
        CkStringBuilder_Dispose(sbSshCert);
        return;
    }

    sbPrivKey = CkStringBuilder_Create();
    success = CkStringBuilder_LoadFile(sbPrivKey,"qa_data/sshKeys/user_ecdsa_key","utf-8");
    if (success == FALSE) {
        printf("Failed to load user_ecdsa_key\n");
        CkStringBuilder_Dispose(sbSshCert);
        CkStringBuilder_Dispose(sbPrivKey);
        return;
    }

    key = CkSshKey_Create();
    // Provide the password if the user_ecdsa_key is stored in an encrypted format.
    CkSshKey_putPassword(key,"secret");
    success = CkSshKey_FromOpenSshPrivateKey(key,CkStringBuilder_getAsString(sbPrivKey));
    if (success == FALSE) {
        printf("%s\n",CkSshKey_lastErrorText(key));
        CkStringBuilder_Dispose(sbSshCert);
        CkStringBuilder_Dispose(sbPrivKey);
        CkSshKey_Dispose(key);
        return;
    }

    // Indicate that the SSH certificate is to be used for authentication.
    // The UseSshCertificate method was added in Chilkat v11.0.0
    CkSshKey_UseSshCertificate(key,CkStringBuilder_getAsString(sbSshCert));

    sftp = CkSFtp_Create();

    hostname = "sftp.example.com";
    port = 22;
    success = CkSFtp_Connect(sftp,hostname,port);
    if (success != TRUE) {
        printf("%s\n",CkSFtp_lastErrorText(sftp));
        CkStringBuilder_Dispose(sbSshCert);
        CkStringBuilder_Dispose(sbPrivKey);
        CkSshKey_Dispose(key);
        CkSFtp_Dispose(sftp);
        return;
    }

    success = CkSFtp_AuthenticatePk(sftp,"myLogin",key);
    if (success != TRUE) {
        printf("%s\n",CkSFtp_lastErrorText(sftp));
        CkStringBuilder_Dispose(sbSshCert);
        CkStringBuilder_Dispose(sbPrivKey);
        CkSshKey_Dispose(key);
        CkSFtp_Dispose(sftp);
        return;
    }

    printf("Public-Key Authentication using an SSH Certificate was Successful!\n");


    CkStringBuilder_Dispose(sbSshCert);
    CkStringBuilder_Dispose(sbPrivKey);
    CkSshKey_Dispose(key);
    CkSFtp_Dispose(sftp);

    }