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

Generate RSA Public/Private Key Pair and Export to PEM

See more RSA Examples

_LANGUAGE_ example code showing how to generate an RSA public/private key pair and export to PEM files.

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 key.  Chilkat RSA supports
-- key sizes ranging from 512 bits to 8192 bits.
local privKey = chilkat.PrivateKey.new()
local success = rsa:gen_key(2048, privKey)
if not success then
    print(rsa.last_error_text)
    return
end

local pubKey = chilkat.PublicKey.new()
privKey:to_public_key(pubKey)

-- Save the private key in PEM format:
success = privKey:save_pem_file("privateKey.pem")
if not success then
    print(privKey.last_error_text)
    return
end

-- Save the public key in PEM format:
success = pubKey:save_pem_file(false, "publicKey.pem")
if not success then
    print(pubKey.last_error_text)
    return
end

print("Success.")