跳至主要內容

lua-openssl 擴充庫

lua-openssl 手冊地址

lua-openssl GitHub 倉庫


XXTouch 已內建 zhaozg/lua-openssl,可直接通過 require("openssl") 使用。

local openssl = require("openssl")

AES-128-ECB 範例

local cipher = require("openssl").cipher

local key = "1234567890abcdef" -- AES-128 需要 16 字節密鑰
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)

AES-128-CBC 範例

local cipher = require("openssl").cipher

local key = "1234567890abcdef" -- AES-128 需要 16 字節密鑰
local iv = "abcdef1234567890" -- AES-128-CBC 需要 16 字節 IV
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)

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)