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

RSA Hash Binary Data and Sign (and Verify)

See more RSA Examples

Demonstrates how to sign the hash of binary data. Also demonstrates how to verify the RSA signature.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

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

-- Load an RSA private key for signing.
local privKey = chilkat.PrivateKey.new()
local success = privKey:load_encrypted_pem_file("qa_data/pem/rsa_passwd.pem", "passwd")
if not success then
    print(privKey.last_error_text)
    return
end

local rsa = chilkat.Rsa.new()
rsa:use_private_key(privKey)

-- We have some binary data (in hex) to sign
local originalData = "0102030405060708090A"
local bdData = chilkat.BinData.new()
bdData:append_encoded(originalData, "hex")

-- Hash (SHA-256) and sign the hash:
local bdSignature = chilkat.BinData.new()
success = rsa:sign_bd(bdData, "sha256", bdSignature)
if not success then
    print(rsa.last_error_text)
    return
end

-- Show the RSA signature in base64
print(bdSignature:get_encoded("base64"))

-- ------------------------------------------
-- Get the public key from the private key
local pubKey = chilkat.PublicKey.new()
privKey:to_public_key(pubKey)

-- Verify the signature..
local rsa2 = chilkat.Rsa.new()
rsa2:use_public_key(pubKey)

local bVerified = rsa2:verify_bd(bdData, "sha256", bdSignature)
print("signature verified: " .. tostring(bVerified))