Sample code for 30+ languages & platforms
PowerBuilder

PKCS11 Generate Secret Key (such as AES)

See more PKCS11 Examples

Generates a symmetric secret key such as AES on the HSM.

Note: This example requires Chilkat v9.5.0.96 or later.

Chilkat PowerBuilder Downloads

PowerBuilder
integer li_rc
integer li_Success
oleobject loo_Pkcs11
string ls_Pin
integer li_UserType
string ls_KeyType
oleobject loo_Json
integer li_KeyHandle

li_Success = 0

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

// Note: Chilkat's PKCS11 implementation runs on Windows, Linux, Mac OS X, and other supported operating systems.

loo_Pkcs11 = create oleobject
li_rc = loo_Pkcs11.ConnectToNewObject("Chilkat.Pkcs11")
if li_rc < 0 then
    destroy loo_Pkcs11
    MessageBox("Error","Connecting to COM object failed")
    return
end if

// Use the PKCS11 driver (.dll, .so, .dylib) for your particular HSM.
// (The format of the path will change with the operating system.  Obviously, "C:/" is not used on non-Windows systems.
loo_Pkcs11.SharedLibPath = "C:/Program Files (x86)/Gemalto/IDGo 800 PKCS#11/IDPrimePKCS1164.dll"

// Establish a logged-on session.
ls_Pin = "0000"
li_UserType = 1
li_Success = loo_Pkcs11.QuickSession(li_UserType,ls_Pin)
if li_Success = 0 then
    Write-Debug loo_Pkcs11.LastErrorText
    destroy loo_Pkcs11
    return
end if

// Let's generate a 256-bit AES key on the token, which will exist for the duration of this session.
// Symmetric keys, such as AES keys, are typically created (or imported) and used during a single session.

// Other possible values for keyType are "AES XTS", "Blowfish", "Twofish", "ChaCha20", and others. 
// In virtually all cases, you'll want to create an AES key.
ls_KeyType = "AES"

// Specify attributes and abilities (how this key can be used) by providing a JSON template.
loo_Json = create oleobject
li_rc = loo_Json.ConnectToNewObject("Chilkat.JsonObject")

// The key can be extracted or wrapped.
loo_Json.UpdateBool("extractable",1)

// Allow the key to be used for encryption, decryption, wrapping other keys, and unwrapping other keys.
loo_Json.UpdateBool("encrypt",1)
loo_Json.UpdateBool("decrypt",1)
loo_Json.UpdateBool("wrap",1)
loo_Json.UpdateBool("unwrap",1)

// Indicate a 256-bit AES key is to be generated by setting the value_len attribute equal to the key size in bytes.
// (32 bytes * 8 bits/byte = 256 bits)
loo_Json.UpdateInt("value_len",32)

li_KeyHandle = loo_Pkcs11.GenSecretKey(ls_KeyType,loo_Json)
if li_KeyHandle = 0 then
    Write-Debug loo_Pkcs11.LastErrorText
    Write-Debug "Failed to generate an AES key."
else
    Write-Debug "key handle = " + string(li_KeyHandle)
    Write-Debug "Success."
end if

loo_Pkcs11.Logout()
loo_Pkcs11.CloseSession()


destroy loo_Pkcs11
destroy loo_Json