Lua Requires Chilkat v11.0.0+
Lua
PKCS11 Import an Existing RSA Public Key onto the HSM
See more PKCS11 Examples
Demonstrates how to import an existing RSA Public Key onto a smart card or token.Chilkat Lua Downloads
local chilkat = require("chilkat")
-- 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.
local pkcs11 = chilkat.Pkcs11.new()
-- 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.
pkcs11.shared_lib_path = "C:/Program Files (x86)/Gemalto/IDGo 800 PKCS#11/IDPrimePKCS1164.dll"
-- Establish a logged-on session.
local pin = "0000"
local userType = 1
local success = pkcs11:quick_session(userType, pin)
if not success then
print(pkcs11.last_error_text)
return
end
-- Generate a new 2048-bit RSA key.
local rsa = chilkat.Rsa.new()
local privKey = chilkat.PrivateKey.new()
success = rsa:gen_key(2048, privKey)
if not success then
print(rsa.last_error_text)
return
end
-- Get the public key information as XML, so we can access the modulus and exponent.
local xml = chilkat.Xml.new()
local pubKey = chilkat.PublicKey.new()
privKey:to_public_key(pubKey)
xml:load_xml(pubKey:get_xml())
local attrs = chilkat.JsonObject.new()
-- Specify the type of object, and the type of key.
attrs:update_string("class", "CKO_PUBLIC_KEY")
attrs:update_string("key_type", "CKK_RSA")
-- Add an optional label if desired.
attrs:update_string("label", "RSA Public Key 1")
-- Allow the key to be use for verify, wrapping, and encryption operations.
attrs:update_bool("verify", true)
attrs:update_bool("wrap", true)
attrs:update_bool("encrypt", true)
-- Make this a session-only public key.
-- To store the public key on the token so that it persists after the PKCS11 session, set token = true.
attrs:update_bool("token", false)
-- Provide the RSA public key material
attrs:update_string("modulus", xml:get_child_content("Modulus"))
attrs:update_string("public_exponent", xml:get_child_content("Exponent"))
-- Create the RSA public key.
-- Returns the PKCS11 object handle of the created key.
local objHandle = pkcs11:create_pkcs11_object(attrs)
if objHandle == 0 then
print(pkcs11.last_error_text)
print("Failed.")
else
print("PKCS11 object handle = " .. objHandle)
print("Successfully imported an RSA key..")
end
pkcs11:logout()
pkcs11:close_session()