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

RSA Encrypt Randomly Generated AES Key

See more RSA Examples

Demonstrates how to RSA encrypt a randomly generated AES key.

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.

-- First generate a 256-bit AES key (32 bytes).
local prng = chilkat.Prng.new()
local bdAesKey = chilkat.BinData.new()
local success = prng:gen_random_bd(32, bdAesKey)

-- Use a public key from a certificate for RSA encryption.
local cert = chilkat.Cert.new()

success = cert:load_from_file("qa_data/pem/mf_public_rsa.pem")
if not success then
    print(cert.last_error_text)
    return
end

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

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

-- RSA encrypt our 32-byte AES key.
-- The contents of bdAesKey are replaced with result of the RSA encryption.
success = rsa:encrypt_bd(bdAesKey, false)
if not success then
    print(rsa.last_error_text)
    return
end

-- Return the result as a base64 string
local encryptedAesKey = bdAesKey:get_encoded("base64")

print("encrypted AES key = " .. encryptedAesKey)