Sample code for 30+ languages & platforms
Xbase++

SFTP Authentication using X.509 Certificates

See more SFTP Examples

Demonstrates how to authenticate with an SSH/SFTP server using an certificate's private key.

Note: See X.509v3 Certificates for SSH Authentication for more information.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oSftp
LOCAL cHostname
LOCAL nPort
LOCAL oCert
LOCAL cPrivKeyPem
LOCAL oKey

nSuccess := 0

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

oSftp := CreateObject("Chilkat.SFtp")

cHostname := "sftp.example.com"
nPort := 22
nSuccess := oSftp:Connect(cHostname, nPort)
IF (nSuccess != 1)
    ? oSftp:LastErrorText
    oSftp:destroy()
    RETURN
ENDIF

//  Load the cert + private key from a .pfx.
//  Note: Chilkat provides methods for loading certs and private keys from many sources, including smart cards and USB tokens (HSM's)
oCert := CreateObject("Chilkat.Cert")
nSuccess := oCert:LoadPfxFile("qa_data/pfx/example.pfx", "pfx_password")
IF (nSuccess != 1)
    ? oCert:LastErrorText
    oSftp:destroy()
    oCert:destroy()
    RETURN
ENDIF

//  Get the cert's private key (as PEM) to be used for SSH authentication.
//  (The public key is installed on the server.)
cPrivKeyPem := oCert:GetPrivateKeyPem()
IF (oCert:LastMethodSuccess == 0)
    ? oCert:LastErrorText
    oSftp:destroy()
    oCert:destroy()
    RETURN
ENDIF

oKey := CreateObject("Chilkat.SshKey")

//  Load a private key from a PEM string:
nSuccess := oKey:FromOpenSshPrivateKey(cPrivKeyPem)
IF (nSuccess != 1)
    ? oKey:LastErrorText
    oSftp:destroy()
    oCert:destroy()
    oKey:destroy()
    RETURN
ENDIF

//  Authenticate with the SSH server.
nSuccess := oSftp:AuthenticatePk("myLogin", oKey)
IF (nSuccess != 1)
    ? oSftp:LastErrorText
    oSftp:destroy()
    oCert:destroy()
    oKey:destroy()
    RETURN
ENDIF

? "Public-Key Authentication Successful!"

oSftp:destroy()
oCert:destroy()
oKey:destroy()