Sample code for 30+ languages & platforms
Lua Requires Chilkat v11.0.0+

RSA Signature/Verify with .key and .cer

See more RSA Examples

Demonstrates how to use a .key file (private key) and digital certificate (.cer, public key) to create and verify an RSA signature.

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 privKey = chilkat.PrivateKey.new()

-- Load the private key from an RSA .key file:
local success = privKey:load_pem_file("privateKey.key")
if not success then
    print(privKey.last_error_text)
    return
end

local rsa = chilkat.Rsa.new()

-- Import the private key into the RSA component:
success = rsa:use_private_key(privKey)
if not success then
    print(rsa.last_error_text)
    return
end

-- Create the signature as a hex string:
rsa.encoding_mode = "hex"

local strData = "This is the string to be signed."

-- Sign the string using the sha256 hash algorithm.
-- Other valid choices are "md2", "sha1", "sha384",
-- "sha512", and "md5".
local hexSig = rsa:sign_string_enc(strData, "sha256")

print(hexSig)

-- Load a digital certificate from a .cer file:
local cert = chilkat.Cert.new()

success = cert:load_from_file("myCert.cer")
if not success then
    print(cert.last_error_text)
    return
end

local pubKey = chilkat.PublicKey.new()
cert:get_public_key(pubKey)

-- Now verify using a new instance of the RSA object:
local rsa2 = chilkat.Rsa.new()

-- Import the public key into the RSA object:
success = rsa2:use_public_key(pubKey)
if not success then
    print(rsa2.last_error_text)
    return
end

-- The signature is a hex string, so make sure the EncodingMode is correct:
rsa2.encoding_mode = "hex"

-- Verify the signature:
success = rsa2:verify_string_enc(strData, "sha256", hexSig)
if not success then
    print(rsa2.last_error_text)
    return
end

print("Success.")