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

Generate RSA Key and Sign a String

See more RSA Examples

Demonstrates how to generate a new RSA public/private key pair and use it to generate a signature for a string. The (binary) digital signature is returned as a hexidecimalized string.

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 rsa = chilkat.Rsa.new()

-- Generate a 2048-bit RSA key.
local privKey = chilkat.PrivateKey.new()
local success = rsa:gen_key(2048, privKey)

rsa:use_private_key(privKey)

-- Return the signature in hex.
rsa.encoding_mode = "hex"

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

-- Sign the SHA256 hash of the string.
local hexSig = rsa:sign_string_enc(strData, "sha256")

print(hexSig)

-- Now verify the signature:
local pubKey = chilkat.PublicKey.new()
privKey:to_public_key(pubKey)
rsa:use_public_key(pubKey)

success = rsa:verify_string_enc(strData, "sha256", hexSig)
if success then
    print("Signature verified!")
else
    print(rsa.last_error_text)
end

-- Try it with an invalid signature:
success = rsa:verify_string_enc(strData, "sha256", "not a valid sig")
if success then
    print("Signature verified!")
else
    print("Signature validation failed!")
end

-- Try it with invalid data:
success = rsa:verify_string_enc("Not the original data", "sha256", hexSig)
if success then
    print("Signature verified!")
else
    print("Signature validation failed!")
end