メインコンテンツまでスキップ

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)