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

RSA Sign Binary Data and Verify (Recover the Original Data)

See more RSA Examples

Demonstrates how to RSA sign binary data and then verify/recover the original data.

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 bd = chilkat.BinData.new()
bd:append_encoded(originalData, "hex")

-- If successful, the contents of bd are replaced with the RSA signature.
success = rsa:sign_raw_bd(bd)
if not success then
    print(rsa.last_error_text)
    return
end

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

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

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

local bVerified = rsa2:verify_raw_bd(bd)
print("signature verified: " .. tostring(bVerified))

-- Show the original data:
print("original data: " .. bd:get_encoded("hex"))