Rsa Lua Reference Documentation
chilkat.Rsa
Current Version: 11.7.0
Markdown version of this page for AI tools (v 11.7.0) · all AI docs
Chilkat.Rsa
Use
Encrypt data with a public key for workflows where only the matching
private key should be able to decrypt the result.
Decrypt RSA-encrypted data using a private key, including keys loaded
directly or accessed through a certificate.
Create and verify RSA signatures over data using the hash algorithm and
padding mode required by the application or protocol.
Sign or verify already-computed message digests when the hashing step is
performed separately or by another component.
Generate RSA key pairs for applications that need new public/private key
material.
Use RSA keys associated with certificates, including non-exportable
private keys in smart cards, USB tokens, Windows stores, or Apple
Keychain.
For an extended overview, see
Rsa Class Overview.
Encrypt, decrypt, sign, verify, and generate RSA keys.
Chilkat.Rsa when an application needs direct RSA
cryptographic operations. It can encrypt data with a public key, decrypt with
a private key, create RSA signatures, verify signatures, sign precomputed
hashes, verify signed hashes, and generate RSA key pairs. It also works with
keys supplied directly as PrivateKey or PublicKey
objects, or indirectly through certificates.
RSA encryption
RSA decryption
Sign and verify data
Sign precomputed hashes
Generate RSA keys
Certificate-backed keys
Chilkat.Rsa for direct RSA operations; use higher-level
classes such as Crypt2, Jws, Jwt, or
Mime when the RSA operation is part of a larger format or
protocol.
Object Creation
local chilkat = require("chilkat")
local rsa = chilkat.Rsa.new()Creates the object (chilkat.Rsa() does the same). Lua's garbage collector frees it when it is no longer referenced; rsa:dispose() frees it at once, and in Lua 5.4 and later local rsa <close> = chilkat.Rsa.new() frees it when the block ends. Calling a method of a disposed object raises an error.
Errors
A method that fails returns nil followed by the error text, as io.open does: local body, err = rsa:method(...), where err is the object's last_error_text. Wrap the call in assert() to raise an error with that text instead. Methods that answer a question return true or false, numbers are returned as they are (check last_method_success where the description says a value means failure), and property reads and writes never fail for Chilkat reasons.
Misuse raises a Lua error: a wrong argument type or a missing argument (bad argument #1 to ...), an unknown property name, a write to a read-only property, an out-of-range integer, or an object of the wrong class.
Names are Chilkat's in snake_case: QuickGetStr is quick_get_str, LastErrorText is last_error_text. Properties are fields (rsa.verbose_logging = true) and methods use the colon (rsa:method(...)). Strings are UTF-8; binary data is a Lua string of bytes. Indexes are 0-based, as in every Chilkat API. Unlocking: call chilkat.unlock_bundle("...") once at startup.
Properties
Charset
local strVal = rsa.charset
rsa.charset = strVal
This property specifies the character encoding used to represent text as bytes for encryption, decryption, signing, and signature validation. By default, it uses the computer's ANSI charset, such as Windows-1252 for locales like the United States, United Kingdom, Western Europe, Australia, and New Zealand.
Most applications are advised to set this property to UTF-8. Chilkat plans to change its default to UTF-8 in a future major version to align with current standards. The current default of ANSI stems from a time when UTF-8 was not widely adopted.
DebugLogFilePath
local strVal = rsa.debug_log_file_path
rsa.debug_log_file_path = strVal
If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. This logging helps identify the context and history of Chilkat calls leading up to any crash or hang, aiding in debugging.
Enabling the VerboseLogging property provides more detailed information. This property is mainly used for debugging rare instances where a Chilkat method call causes a hang or crash, which should generally not happen.
Possible causes of hangs include:
- A timeout property set to 0, indicating an infinite timeout.
- A hang occurring within an event callback in the application code.
- An internal bug in the Chilkat code causing the hang.
EncodingMode
local strVal = rsa.encoding_mode
rsa.encoding_mode = strVal
This property defines the encoding for methods ending in ENC, such as EncryptStringENC. Valid modes include base64, hex, hex_lower, and more. The encoding mode applies to signatures, encrypted data, and hashes used in or returned by a method.
LastErrorHtml
local strVal = rsa.last_error_html
Provides HTML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastErrorText
local strVal = rsa.last_error_text
Provides plain text information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
LastErrorXml
local strVal = rsa.last_error_xml
Provides XML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastMethodSuccess
local boolVal = rsa.last_method_success
rsa.last_method_success = boolVal
Indicates the success or failure of the most recent method call: true means success, false means failure. This property remains unchanged by property setters or getters. This method is present to address challenges in checking for null or Nothing returns in certain programming languages. Note: This property does not apply to methods that return integer values or to boolean-returning methods where the boolean does not indicate success or failure.
LittleEndian
local boolVal = rsa.little_endian
rsa.little_endian = boolVal
When creating RSA signatures, this property determines the endianness: set it to true for little-endian signatures and false for big-endian signatures.
NoUnpad
local boolVal = rsa.no_unpad
rsa.no_unpad = boolVal
If true, skips unpadding when decrypting. The default is false. This property value is typically left unchanged.
NumBits
local intVal = rsa.num_bits
The bit length, such as 2048, of the imported or generated RSA key.
topOaepHash
local strVal = rsa.oaep_hash
rsa.oaep_hash = strVal
Selects the hash algorithm for use within OAEP padding for encryption. The valid choices are sha256, sha384, sha512, or sha1.
The default is SHA1. You'll likely want to change this to to SHA256. The next major version of Chilkat (11.0.0) will change the default to SHA256.
OaepLabel
local strVal = rsa.oaep_label
rsa.oaep_label = strVal
The optional RSA encryption OAEP label is a hex representation of the label bytes used for encrypting with OAEP padding. Typically, this is left empty (0 bytes) unless there's a specific requirement to set it.
OaepMgfHash
local strVal = rsa.oaep_mgf_hash
rsa.oaep_mgf_hash = strVal
Selects the MGF (mask generation) hash algorithm for use within OAEP padding for encryption. The valid choices are sha256, sha384, sha512, or sha1.
Note: This property should typically be set to the same value as the OaepHash property. Many software implementations are not able to handle cases where the MGF hash is different than the OAEP hash.
The default is SHA1. You'll likely want to change this to to SHA256. The next major version of Chilkat (11.0.0) will change the default to SHA256.
PkcsPadding
local boolVal = rsa.pkcs_padding
rsa.pkcs_padding = boolVal
This property controls padding for both signing and encryption. The default value is true, which is to use PKCS#1 v1.5 padding. If set to false, then PSS padding is used for signatures and OAEP padding is used for encryption.
This property replaces the deprecated OaepPadding property. Until the OaepPadding property is removed, setting this property will automatically set OaepPadding to the opposite, and vice-versa. This is to maintain backward compatibility until applications can switch to using this new property.
PssSaltLen
local intVal = rsa.pss_salt_len
rsa.pss_salt_len = intVal
When using RSASSA-PSS padding for signatures, you can choose the PSS salt length. By default, the salt length is set to -1, which uses the length of the hash function. For instance, with the SHA256 hash function, the salt length will be 32 bytes. You can specify a different salt length, like 20 bytes, if needed, but it's generally recommended to keep the default setting.
topUncommonOptions
local strVal = rsa.uncommon_options
rsa.uncommon_options = strVal
This is a catch-all property to be used for uncommon needs. This property defaults to the empty string and should typically remain empty.
topVerboseLogging
local boolVal = rsa.verbose_logging
rsa.verbose_logging = boolVal
If set to true, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is false. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.
Version
local strVal = rsa.version
Methods
DecryptBd
-- use_private_key is a boolean
-- ok is true, or nil and err on failure
local ok, err = rsa:decrypt_bd(bd, use_private_key)
RSA decrypts the contents of bd. use_private_key should be set to true if the private key is to be used for decrypting. Otherwise it should be set to false if (in rare cases) the public key is to be used for decrypting.
Important: If trying to match OpenSSL results, set the LittleEndian property = false.
Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
DecryptStringENC
-- use_private_key is a boolean
-- str is a string, or nil and err on failure
local str, err = rsa:decrypt_string_enc(str, use_private_key)
Decrypts str with the RSA algorithm. str is the encoded form of the encrypted binary data. The EncodingMode property defines str's encoding. The Charset property specifies the byte representation for interpreting the decrypted text. Set use_private_key to true to use the private key for decryption; otherwise, set use_private_key to false to use the public key (used rarely). Returns the decrypted string.
Important: If trying to match OpenSSL results, set the LittleEndian property = false.
Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
EncryptBd
-- use_private_key is a boolean
-- ok is true, or nil and err on failure
local ok, err = rsa:encrypt_bd(bd, use_private_key)
RSA encrypts the contents of bd. Set use_private_key to false to use the public key for encrypting; otherwise, set it to true to use the private key (in rare cases).
Important: If trying to match OpenSSL results, set the LittleEndian property = false.
Note: The public key's role is to make encryption accessible to anyone while ensuring that only the private key holder can decrypt the messages. The public key is designed to be widely distributed so anyone can use it to encrypt messages intended for the owner of the private key.
Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
EncryptStringENC
-- b_use_private_key is a boolean
-- str is a string, or nil and err on failure
local str, err = rsa:encrypt_string_enc(str, b_use_private_key)
Encrypts str with the RSA algorithm. The Charset property specifies the byte representation of the string that is encrypted. Set b_use_private_key to false to use the public key for encrypting; otherwise, set it to true to use the private key (in rare cases). The encrypted data is returned in the format specified by the EncodingMode property.
Important: If trying to match OpenSSL results, set the LittleEndian property = false.
Note: The public key's role is to make encryption accessible to anyone while ensuring that only the private key holder can decrypt the messages. The public key is designed to be widely distributed so anyone can use it to encrypt messages intended for the owner of the private key.
Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
GenKey
-- priv_key is a chilkat.PrivateKey
-- ok is true, or nil and err on failure
local ok, err = rsa:gen_key(num_bits, priv_key)
Generates a new RSA key and stores it in priv_key. num_bits specifies the key length, which can range from 512 to 8192 bits. Common key lengths are 1024, 2048, or 4096 bits.
Note: Generating an 8192-bit key may take a significant amount of time. The method does not support event callbacks or progress monitoring and will block the thread until completion.
Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
SetX509Cert
-- use_private_key is a boolean
-- ok is true, or nil and err on failure
local ok, err = rsa:set_x509_cert(cert, use_private_key)
Provides the private or public key indirectly through a certificate. This method is used when the private key is inaccessible, such as when stored on a smart card, USB token, in the Windows registry (marked as non-exportable), or in the Apple Keychain.
Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
SignBd
-- hash_algorithm is a string
-- bd_sig is a chilkat.BinData
-- ok is true, or nil and err on failure
local ok, err = rsa:sign_bd(bd_data, hash_algorithm, bd_sig)
Generates an RSA digital signature by first hashing the contents of bd_data with the hash algorithm specified by hash_algorithm, which can be sha256, sha384, sha512, or sha1. The resulting signature is written to bd_sig.
Note: It is important to be aware of endianness. Make sure the LittleEndian property is set according to your specific needs.
Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
SignHashENC
-- hash_alg is a string
-- str is a string, or nil and err on failure
local str, err = rsa:sign_hash_enc(encoded_hash, hash_alg)
This function creates an RSA digital signature for the hash provided in encoded_hash, which should be encoded according to the EncodingMode setting (e.g., base64 if EncodingMode = base64). hash_alg specifies the hash algorithm and can be sha256, sha384, sha512, or sha1. The function returns the signature encoded as specified by EncodingMode.
Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
SignRawBd
-- ok is true, or nil and err on failure
local ok, err = rsa:sign_raw_bd(bd)
This is legacy low-level raw RSA that duplicates the (now deprecated) OpenSSL rsautl utility. It directly signs raw data rather than signing a hash of the data. PKCS#1 v1.5 padding is always used. The data to be signed is passed in bd, and on return the content of bd is replaced with the RSA signed data.
Note: It is possible to validate and recover the original data by calling VerifyRawBd.
Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
SignStringENC
-- hash_algorithm is a string
-- str is a string, or nil and err on failure
local str, err = rsa:sign_string_enc(str_to_be_hashed, hash_algorithm)
Generates an RSA digital signature by first hashing str_to_be_hashed with the hash algorithm specified by hash_algorithm, which can be sha256, sha384, sha512, or sha1. Returns the signature encoded based on the EncodingMode property.
Note: It is important to be aware of endianness. Make sure the LittleEndian property is set according to your specific needs.
Note: It is recommended to set the Charset property equal to utf-8 before signing strings.
Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
SnkToXml
-- str is a string, or nil and err on failure
local str, err = rsa:snk_to_xml(filename)
Imports a .snk file to an XML document that can be imported via the ImportPrivateKey method.
Returns the string, or nil, err on failure (or when nothing is found). The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
UsePrivateKey
-- ok is true, or nil and err on failure
local ok, err = rsa:use_private_key(priv_key)
Imports a private key from priv_key to use for signing or decrypting.
Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
UsePublicKey
-- ok is true, or nil and err on failure
local ok, err = rsa:use_public_key(pub_key)
Imports a public key from pub_key to use for encrypting or signature verification.
Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
VerifyBd
-- hash_algorithm is a string
-- bd_sig is a chilkat.BinData
-- ok is true, or nil and err on failure
local ok, err = rsa:verify_bd(bd_data, hash_algorithm, bd_sig)
Verifies the RSA signature passed in bd_sig against the original data passed in bd_data. The original data passed in bd_data is hashed using the hash algorithm passed in hash_algorithm (such as sha256, sha384, sha512, or sha1). Returns true if the signature is validated, and false if not.
Note: Knowing the exact hash algorithm used to create the signature is not required. If the signature is not validated using the hash algorithm specified in hash_algorithm, Chilkat will automatically try validating using the other supported algorithms and return success if any validate.
Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
VerifyHashENC
-- hash_alg is a string
-- encoded_sig is a string
-- ok is true, or nil and err on failure
local ok, err = rsa:verify_hash_enc(encoded_hash, hash_alg, encoded_sig)
Validates an RSA signature provided in encoded_sig against the hash of the original data in encoded_hash. Returns true if validation is successful, otherwise returns false. hash_alg specifies the hash algorithm used for encoded_hash, such as sha256, sha384, sha512, or sha1. Ensure the hash's size (e.g., 32 bytes for sha256, 48 bytes for sha384, 64 bytes for sha512, 20 bytes for sha1) matches that of encoded_hash.
Both encoded_hash and encoded_sig should be encoded according to the EncodingMode property (e.g., base64 if EncodingMode = base64)
Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
VerifyRawBd
-- ok is true, or nil and err on failure
local ok, err = rsa:verify_raw_bd(bd)
This is legacy low-level raw RSA that duplicates the (now deprecated) OpenSSL rsautl utility. It validates signed raw data and recovers the original data. The RSA signature to be verified is passed in bd, and on return the content of bd is replaced with the original data.
Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.
VerifyStringENC
-- hash_algorithm is a string
-- encoded_sig is a string
-- ok is true, or nil and err on failure
local ok, err = rsa:verify_string_enc(original_string, hash_algorithm, encoded_sig)
Verifies the encoded RSA signature passed in encoded_sig against the original data passed in original_string. The original data passed in original_string is hashed using the hash algorithm passed in hash_algorithm (such as sha256, sha384, sha512, or sha1). Returns true if the signature is validated, and false if not.
The signature passed in encoded_sig should be encoded according to the EncodingMode property (e.g., base64 if EncodingMode = base64)
Note: Knowing the exact hash algorithm used to create the signature is not required. If the signature is not validated using the hash algorithm specified in hash_algorithm, Chilkat will automatically try validating using the other supported algorithms and return success if any validate.
Returns true on success, nil, err on failure. The second return value, err, is the object's last_error_text; wrap the call in assert() to raise an error instead.