Lua on OS 8.0.0 or later can compute AES authentication codes and perform authenticated encryption for device protocols. Pass binary strings for keys, nonces, data and tags.
| Function | Successful result |
|---|---|
crypto.aesCmac(key, data) |
A 16-byte authentication code. |
crypto.aesCcmEncrypt(key, nonce, aad, plaintext, tagLength) |
Ciphertext followed by the authentication tag. |
crypto.aesCcmDecrypt(key, nonce, aad, ciphertext, tag) |
The plaintext after successful tag verification. |
Keys are 16, 24 or 32 bytes. CCM accepts nonces of 7–13 bytes and even tag lengths from 4 to 16 bytes. Pass "" if the protocol uses no additional authenticated data (AAD). Use a different nonce for each encryption under the same key.
local function openMessage(key, nonce, aad, sealed, tagLength)
local ciphertext = sealed:sub(1, #sealed - tagLength)
local tag = sealed:sub(-tagLength)
return crypto.aesCcmDecrypt(key, nonce, aad, ciphertext, tag)
end
Invalid argument lengths raise a Lua error. A tag mismatch or cryptographic failure returns nil, errorCode. Check the result before using the plaintext.
P-256 key agreement and key derivation
On OS 8.0.0 or later with these functions, all ESP32-based products can use them without starting BLE. Keys and output values are binary strings. A P-256 public key is the 32-byte big-endian X coordinate followed by the 32-byte big-endian Y coordinate, with no leading 0x04 byte.
| Function | Successful result |
|---|---|
crypto.ecdhGenerateKeyPair("P-256") |
A table containing privateKey (32 bytes) and publicKey (64 bytes). |
crypto.ecdhPublicKey("P-256", privateKey) |
The public key corresponding to the supplied private key. |
crypto.ecdhSharedSecret("P-256", privateKey, peerPublicKey) |
A 32-byte shared secret computed after validating the peer public key. |
crypto.hkdfSha256(secret, salt, info, length) |
A key of length bytes (0–8160) derived with HKDF-SHA256. Pass "" for an empty salt or info. |
Signing with the device key
crypto.signWithDeviceKey(data) signs a Lua string using the device's provisioned private key and returns a variable-length DER signature as a binary string. It works offline and accepts embedded NUL bytes. Failure returns nil, error. A missing key returns nil, ENOENT.
Verify using the trusted public key for the device ID. Concatenate the ASCII string obniz.lua.device-sign.v1, one 0x00 byte and the original data, then verify those bytes using ECDSA P-192 (secp192r1) with SHA-256. Getting the device ID