Sample code for 30+ languages & platforms
Lua

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 Lua Downloads

Lua
local chilkat = require("chilkat")

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

local sftp = chilkat.SFtp.new()

local hostname = "sftp.example.com"
local port = 22
local success = sftp:connect(hostname, port)
if not success then
    print(sftp.last_error_text)
    return
end

-- 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)
local cert = chilkat.Cert.new()
success = cert:load_pfx_file("qa_data/pfx/example.pfx", "pfx_password")
if not success then
    print(cert.last_error_text)
    return
end

-- Get the cert's private key (as PEM) to be used for SSH authentication.
-- (The public key is installed on the server.)
local privKeyPem = cert:get_private_key_pem()
if not cert.last_method_success then
    print(cert.last_error_text)
    return
end

local key = chilkat.SshKey.new()

-- Load a private key from a PEM string:
success = key:from_open_ssh_private_key(privKeyPem)
if not success then
    print(key.last_error_text)
    return
end

-- Authenticate with the SSH server.
success = sftp:authenticate_pk("myLogin", key)
if not success then
    print(sftp.last_error_text)
    return
end

print("Public-Key Authentication Successful!")