Saltar al contenido principal

Biblioteca de extensiones lua-openssl

Manual de lua-openssl

Repositorio de lua-openssl en GitHub


XXTouch integra zhaozg/lua-openssl; puedes usarlo directamente mediante require("openssl").

local openssl = require("openssl")

Ejemplo de AES-128-ECB

local cipher = require("openssl").cipher

local key = "1234567890abcdef" -- AES-128 requiere una clave de 16 bytes
local plaintext = "hello xxtouch"

local encrypted = assert(cipher.encrypt("aes-128-ecb", plaintext, key))
local decrypted = assert(cipher.decrypt("aes-128-ecb", encrypted, key))

assert(decrypted == plaintext)

Ejemplo de AES-128-CBC

local cipher = require("openssl").cipher

local key = "1234567890abcdef" -- AES-128 requiere una clave de 16 bytes
local iv = "abcdef1234567890" -- AES-128-CBC requiere un IV de 16 bytes
local plaintext = "hello xxtouch"

local encrypted = assert(cipher.encrypt("aes-128-cbc", plaintext, key, iv))
local decrypted = assert(cipher.decrypt("aes-128-cbc", encrypted, key, iv))

assert(decrypted == plaintext)

Ejemplo de AES-128-GCM

local openssl = require("openssl")
local cipher = openssl.cipher

local evp = assert(cipher.get("aes-128-gcm"))
local key = openssl.random(16)
local iv = openssl.random(12)
local aad = "xxtouch"
local plaintext = "hello xxtouch"
local tag_len = 16

local enc = assert(evp:encrypt_new())
assert(enc:ctrl(cipher.EVP_CTRL_GCM_SET_IVLEN, #iv))
assert(enc:init(key, iv))
assert(enc:update(aad, true))
local encrypted = assert(enc:update(plaintext))..assert(enc:final())
local tag = assert(enc:ctrl(cipher.EVP_CTRL_GCM_GET_TAG, tag_len))

local dec = assert(evp:decrypt_new())
assert(dec:ctrl(cipher.EVP_CTRL_GCM_SET_IVLEN, #iv))
assert(dec:init(key, iv))
assert(dec:update(aad, true))
local decrypted = assert(dec:update(encrypted))
assert(dec:ctrl(cipher.EVP_CTRL_GCM_SET_TAG, tag))
decrypted = decrypted..assert(dec:final())

assert(decrypted == plaintext)