Unicode C
Unicode C
SSH HSM Public Key Authentication
See more uncategorized Examples
Demonstrates how to authenticate with an SSH server using public key authentication using an HSM (USB token or smartcard).Chilkat Unicode C Downloads
#include <C_CkPkcs11W.h>
#include <C_CkJsonObjectW.h>
#include <C_CkSshKeyW.h>
#include <C_CkSshW.h>
void ChilkatSample(void)
{
BOOL success;
HCkPkcs11W pkcs11;
const wchar_t *pin;
int userType;
HCkJsonObjectW json;
unsigned long priv_handle;
unsigned long pub_handle;
HCkSshKeyW key;
const wchar_t *keyType;
HCkSshW ssh;
success = FALSE;
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Note: Chilkat's PKCS11 implementation runs on Windows, Linux, MacOs, and other supported operating systems.
pkcs11 = CkPkcs11W_Create();
// This would be a path to a .dylib on MacOS, or a path to a .so shared lib on Linux.
CkPkcs11W_putSharedLibPath(pkcs11,L"C:/Program Files (x86)/Gemalto/IDGo 800 PKCS#11/IDPrimePKCS1164.dll");
pin = L"0000";
userType = 1;
// Establish a PKCS11 logged-on session using the driver (.so, .dylib, or .dll) as specified in the SharedLibPath above.
success = CkPkcs11W_QuickSession(pkcs11,userType,pin);
if (success == FALSE) {
wprintf(L"%s\n",CkPkcs11W_lastErrorText(pkcs11));
CkPkcs11W_Dispose(pkcs11);
return;
}
// Set PKCS11 attributes to find our desired private key object.
json = CkJsonObjectW_Create();
CkJsonObjectW_UpdateString(json,L"class",L"private_key");
CkJsonObjectW_UpdateString(json,L"label",L"MySshKey");
// Get the PKCS11 handle to the private key located on the HSM.
priv_handle = CkPkcs11W_FindObject(pkcs11,json);
// Get the PKCS11 handle to the corresponding public key located on the HSM.
CkJsonObjectW_UpdateString(json,L"class",L"public_key");
pub_handle = CkPkcs11W_FindObject(pkcs11,json);
key = CkSshKeyW_Create();
// The key type can be "rsa" or "ec"
keyType = L"rsa";
success = CkSshKeyW_UsePkcs11(key,pkcs11,priv_handle,pub_handle,keyType);
if (success == FALSE) {
wprintf(L"%s\n",CkSshKeyW_lastErrorText(key));
CkPkcs11W_Dispose(pkcs11);
CkJsonObjectW_Dispose(json);
CkSshKeyW_Dispose(key);
return;
}
ssh = CkSshW_Create();
success = CkSshW_Connect(ssh,L"example.com",22);
if (success != TRUE) {
wprintf(L"%s\n",CkSshW_lastErrorText(ssh));
CkPkcs11W_Dispose(pkcs11);
CkJsonObjectW_Dispose(json);
CkSshKeyW_Dispose(key);
CkSshW_Dispose(ssh);
return;
}
// Authenticate with the SSH server using the login and
// HSM private key. (The corresponding public key should've
// been installed on the SSH server beforehand.)
success = CkSshW_AuthenticatePk(ssh,L"myLogin",key);
if (success != TRUE) {
wprintf(L"%s\n",CkSshW_lastErrorText(ssh));
CkPkcs11W_Dispose(pkcs11);
CkJsonObjectW_Dispose(json);
CkSshKeyW_Dispose(key);
CkSshW_Dispose(ssh);
return;
}
wprintf(L"Public-Key Authentication Successful!\n");
CkPkcs11W_Dispose(pkcs11);
CkJsonObjectW_Dispose(json);
CkSshKeyW_Dispose(key);
CkSshW_Dispose(ssh);
}