Cipher.constructor(algorithm, key, [iv], [mode]) constructor
The Cipher constructor returns a Cipher instance representing a cryptographic algorithm to be used for encryption/decryption, with the provided key.
Parameters
algorithm
A string representing the algorithm to be used for encryption/decryption :
- "aes128" : advanced encryption standard with 128 bits (16 bytes) key length (block cipher)
- "aes192" : advanced encryption standard with 192 bits (24 bytes) key length (block cipher)
- "aes256" : advanced encryption standard with 256 bits (32 bytes) key length (block cipher)
- "des" : data encryption standard with 56 bits (7 bytes) key length (block cipher)
- "2des": double data encryption standard with 112 bits (14 bytes) key length (block cipher)
- "3des" : triple data encryption standard with 168 bits (21 bytes) key length (block cipher)
- "rc2" : Rivest cipher 2 with 40 to 128 bits (5...16 bytes) key length (block cipher)
- "rc4" : Rivest cipher 4 with 40 to 128 bits (5...16 bytes) key length (stream cipher)
key
A string or a Buffer value, containing the key. If the key is longer than the expected key length, only the first given bytes are used. An error occurs if the key length is too small.
[iv]
A optional string or Buffer value, containing an initialization vector.
[mode]
A string representing the algorithm to be used for encryption/decryption :
- "cbc" : cipher block chaining mode (the default for block algorithms)
- "cfb" : cipher feedback mode
- "ecb" : electronic codebook mode
- "cts" : ciphertext stealing mode
Example
-- Command line encrypter
local crypto = require "crypto"
local console = require "console"
console.clear()
console.writecolor("cyan", "LuaRT console encrypter\n")
local algorithm = console.readln("\nEnter the encryption algorithm: ")
console.echo = "*"
local key = console.readln("Enter the key (or empty to autogenerate): ")
if key == "" then
key = crypto.generate(32)
end
console.echo = true
local iv
if algorithm ~= "rc4" then
iv = console.readln("Enter an initialization vector (or empty if not needed): ")
if iv == "" then
iv = nil
end
end
local mode = console.readln("Enter the cipher mode (or empty to use default): ")
if mode == "" then
mode = nil
end
-- create the cipher
local cipher = crypto.Cipher(algorithm, key, iv, mode)
-- encrypt the message
local nbytes = cipher:encrypt(console.readln("Enter the message to encrypt: "))
console.write("\nSuccessfully encrypted ")
console.writecolor("red", nbytes)
console.writeln(" bytes :")
-- prints the encrypted result
console.writecolor("green", cipher.encrypted:encode("base64"), "\n")