lua-openssl
Kho lưu trữ GitHub của lua-openssl
XXTouch bao gồm zhaozg/lua-openssl, có thể sử dụng trực tiếp bằng cách require("openssl").
local openssl = require("openssl")
Ví dụ AES-128-ECB
local cipher = require("openssl").cipher
local key = "1234567890abcdef" -- AES-128 yêu cầu một khóa 16 byte
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)
Ví dụ AES-128-CBC
local cipher = require("openssl").cipher
local key = "1234567890abcdef" -- AES-128 yêu cầu một khóa 16 byte
local iv = "abcdef1234567890" -- AES-128-CBC yêu cầu một IV 16 byte
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)
Ví dụ 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)