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

RSA Sign with PKCS8 Encrypted Key

See more RSA Examples

Demonstrates how to load a private key from an encrypted PKCS8 file and create an RSA digital signature (and then verify it).

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 PEM file:
local success = privKey:load_any_format_file("raul_privateKey.key", "a0123456789")
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

-- This example will sign a string, and receive the signature
-- in a hex-encoded string.  Therefore, set the encoding mode
-- to "hex":
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 sha1, sha384, sha512 and others.
local hexSig = rsa:sign_string_enc(strData, "sha256")
if not rsa.last_method_success then
    print(rsa.last_error_text)
    return
end

print(hexSig)

-- Now verify with the public key.
-- This example shows how to use the public key from
-- a digital certificate (.cer file)
local cert = chilkat.Cert.new()
success = cert:load_from_file("raul_publicKey.cer")
if not success then
    print(cert.last_error_text)
    return
end

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

local rsa2 = chilkat.Rsa.new()
success = rsa2:use_public_key(pubKey)
if not success then
    print(rsa2.last_error_text)
    return
end

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

print("Signature verified!")

-- Verify with incorrect data:
success = rsa2:verify_string_enc("something else", "sha256", hexSig)
if not success then
    print("Signature not verified! (which was expected in this case)")
else
    print("Hmmm... that's not right...")
end