React Native
React Native
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 React Native Downloads
import { Cert, SFtp, SshKey } from '@chilkat/react-native'
async function chilkatExample() {
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
const sftp = new SFtp();
const hostname = 'sftp.example.com';
const port = 22;
try {
await sftp.connectAsync(hostname, port);
} catch {
console.log(sftp.lastErrorText);
return;
}
// 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)
const cert = new Cert();
try {
cert.loadPfxFile('qa_data/pfx/example.pfx', 'pfx_password');
} catch {
console.log(cert.lastErrorText);
return;
}
// Get the cert's private key (as PEM) to be used for SSH authentication.
// (The public key is installed on the server.)
let privKeyPem: string;
try {
privKeyPem = cert.getPrivateKeyPem();
} catch {
console.log(cert.lastErrorText);
return;
}
const key = new SshKey();
// Load a private key from a PEM string:
try {
key.fromOpenSshPrivateKey(privKeyPem);
} catch {
console.log(key.lastErrorText);
return;
}
// Authenticate with the SSH server.
try {
await sftp.authenticatePkAsync('myLogin', key);
} catch {
console.log(sftp.lastErrorText);
return;
}
console.log('Public-Key Authentication Successful!');
}