Lua Requires Chilkat v11.0.0+
Lua
Generate an RSA Key and Save to Encrypted PEM
See more RSA Examples
Demonstrates how to generate an RSA key and save to an encrypted PEM file.Chilkat Lua Downloads
local chilkat = require("chilkat")
local rsa = chilkat.Rsa.new()
-- Generate a 2048-bit key.
local privKey = chilkat.PrivateKey.new()
local success = rsa:gen_key(2048, privKey)
if not success then
print(rsa.last_error_text)
return
end
local password = "secret"
-- Saving to a relative path (from the current working directory of the process).
local path = "rsaKeys/myTestRsaPrivate.pem"
-- Encrypt the PEM using 256-bit AES encryption.
privKey.pkcs8_encrypt_alg = "aes256"
success = privKey:save_pkcs8_encrypted_pem_file(password, path)
if not success then
print(privKey.last_error_text)
return
end
--
-- We can also save the public key.
-- There is no need to encrypt public keys.
local pubKey = chilkat.PublicKey.new()
privKey:to_public_key(pubKey)
path = "rsaKeys/myTestRsaPublic.pem"
-- Choose PKCS1 or PKCS8
-- We'll choose PKCS8.
local preferPkcs1 = false
success = pubKey:save_pem_file(preferPkcs1, path)
if not success then
print(pubKey.last_error_text)
return
end
--
print("Success.")