https://github.com/zhaozg/lua-openssl
Openssl binding for Lua
https://github.com/zhaozg/lua-openssl
c cipher crypto lua lua-openssl luajit openssl openssl-binding ssl
Last synced: 4 days ago
JSON representation
Openssl binding for Lua
- Host: GitHub
- URL: https://github.com/zhaozg/lua-openssl
- Owner: zhaozg
- License: other
- Created: 2011-07-02T11:15:48.000Z (over 14 years ago)
- Default Branch: master
- Last Pushed: 2025-03-24T03:52:27.000Z (10 months ago)
- Last Synced: 2025-04-01T07:44:37.533Z (10 months ago)
- Topics: c, cipher, crypto, lua, lua-openssl, luajit, openssl, openssl-binding, ssl
- Language: C
- Homepage: https://zhaozg.github.io/lua-openssl/index.html
- Size: 3.2 MB
- Stars: 286
- Watchers: 15
- Forks: 117
- Open Issues: 5
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
lua-openssl toolkit - A free, MIT-licensed OpenSSL binding for Lua.
[](https://github.com/zhaozg/lua-openssl/actions/workflows/ci.yml)
[](https://github.com/zhaozg/lua-openssl/actions/workflows/libressl.yml)
[](https://coveralls.io/github/zhaozg/lua-openssl?branch=master)
[](https://luarocks.org/modules/zhaozg/openssl)
# Index
1. [Introduction](#introduction)
2. [Quick Start](#quick-start)
3. [Documentation](#documentation)
4. [Howto](#howto)
5. [Examples](#example-usage)
## Introduction
I needed a full OpenSSL binding for Lua, after googled, I couldn't find a version
to fit my needs. I found the PHP openssl binding is a good implementation, and it
inspired me. So I decided to write this OpenSSL toolkit for Lua.
The goal is to fully support openssl, include:
- ASN1 Process.
- Symmetrical encrypt/decrypt.
- Message digest.
- Asymmetrical encrypt/decrypt/sign/verify/seal/open.
- X509 certificate.
- PKCS7/CMS.
- SSL/TLS.
## Quick Start
### Dependencies
- Requires [Lua](https://www.lua.org/) 5.1/5.2/5.3/5.4 or [luajit](http://luajit.org/) 2.0/2.1.
- Requires [OpenSSL](https://www.openssl.org/) >= 1.0.0 or [LibreSSL](https://www.libressl.org/) >= v3.3.6.
- On MacOS, you can install dependencies via Homebrew:
```bash
brew install openssl lua
luarocks install openssl
```
It is recommended to use the most up-to-date OpenSSL version because of the
recent security fixes.
### Quick Example
```lua
local openssl = require('openssl')
local md = openssl.digest.get('sha256')
local hash = md:digest('hello world')
print(openssl.hex(hash))
```
See more examples in the \"Example usage\" section below.
Most of the lua-openssl functions require a key or certificate as argument, to
make things easy to use OpenSSL.
This rule allows you to specify certificates or keys in the following ways:
1. As an openssl.x509 object returned from `openssl.x509.read`
2. As an openssl.evp_pkey object return from `openssl.pkey.read` or `openssl.pkey.new`
Similarly, you can also specify a public key as a key object returned from
`x509:get_public()`.
### lua-openssl modules
Module overview:
- digest: message digest algorithms (md5, sha256, etc.)
- cipher: symmetric encryption/decryption (aes, des, etc.)
- x509: certificate parsing and manipulation
- pkcs7/cms: PKCS7/CMS format handling
- bio: memory/file/network data streams
- ssl: SSL/TLS protocol support
- hmac: HMAC authentication
- kdf: key derivation functions (pbkdf2, hkdf, scrypt, etc.) - see [KDF_USAGE.md](./docs/KDF_USAGE.md)
```lua
local digest = require'openssl'.digest
local cipher = require'openssl'.cipher
local kdf = require'openssl'.kdf
```
digest() equals with digest.digest(), same cipher() equals with cipher.cipher().
## Documentation
Document please see [here](http://zhaozg.github.io/lua-openssl/index.html),
that are generated by [LDoc](https://github.com/stevedonovan/LDoc).
Notice: Documentation quality is low and stale, feel free to make a PR to improve it.
If documentation is missing, refer to the [source code](./src) or check the Lua test scripts in the test directory.
### Development Roadmap
For the project's development plan and priorities:
- **[ROADMAP.md](./ROADMAP.md)** - Complete development roadmap (English)
- **[ROADMAP_CN.md](./ROADMAP_CN.md)** - 开发路线图 (Chinese)
- **[DEPRECATION_STATUS.md](./DEPRECATION_STATUS.md)** - Deprecation warning status
### Documentation Coverage
The project includes an automated LDoc analyzer that scans all C source files to check documentation coverage. Current statistics:
- **93.1%** of exported API functions are documented
- **97.9%** of LDoc comments are valid and well-formed
- **768** total LDoc comment blocks across 37 C files
To check documentation coverage:
```bash
make check
```
### lua-openssl Objects
The following are some important lua-openssl object types:
```text
openssl.bio,
openssl.x509,
openssl.stack_of_x509,
openssl.x509_req,
openssl.evp_pkey,
openssl.evp_digest,
openssl.evp_cipher,
openssl.engine,
openssl.pkcs7,
openssl.cms,
openssl.evp_cipher_ctx,
openssl.evp_digest_ctx
...
```
They are shortened as bio, x509, sk_x509, csr, pkey, digest, cipher,
engine, cipher_ctx, and digest_ctx.
### openssl.bn
- **_openssl.bn_** come from [lbn](http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/#lbn), and thanks.
openssl.bn is a big-number library for Lua 5.1. It handles only integers and is
suitable for number-theoretical and cryptographic applications. It is based
on the bn subsystem of OpenSSL cryptographic library:
[bn.h](https://github.com/openssl/openssl/blob/OpenSSL_1_0_2-stable/crypto/bn/bn.h)
If you're running Unix, you probably already have OpenSSL installed.
To try the library, just edit Makefile to reflect your installation of Lua and
then run make. This will build the library and run a simple test. For detailed
installation instructions, see
[lbn](http://webserver2.tecgraf.puc-rio.br/~lhf/ftp/lua/index.html#lbn)
There is no manual but the library is simple and intuitive; see the summary
below.
bn library:
```text
__add(x,y) compare(x,y) pow(x,y)
__div(x,y) div(x,y) powmod(x,y,m)
__eq(x,y) divmod(x,y) random(bits)
__lt(x,y) gcd(x,y) rmod(x,y)
__mod(x,y) invmod(x) sqr(x)
__mul(x,y) isneg(x) sqrmod(x)
__pow(x,y) isodd(x) sqrtmod(x)
__sub(x,y) isone(x) sub(x,y)
__tostring(x) isprime(x,[checks]) submod(x,y,m)
__unm(x) iszero(x) text(t)
abs(x) mod(x,y) tohex(x)
add(x,y) mul(x,y) tonumber(x)
addmod(x,y,m) mulmod(x,y,m) tostring(x)
aprime(bits) neg(x) totext(x)
bits(x) number(x) version
```
### Version
You can get version of lua-openssl, lua and OpenSSL from a Lua script.
```lua
openssl = require "openssl"
-- get version string format
lua_openssl_version, lua_version, openssl_version = openssl.version()
-- get version number format
lua_openssl_version, lua_version, openssl_version = openssl.version(true)
```
### Style
Source code of lua-openssl tidy with [ClangFormat](https://clang.llvm.org/docs/ClangFormat.html)
`clang-format --style=file src/*.c`
### Bugs
Lua-Openssl is heavily updated, if you find a bug, please report to
[here](https://github.com/zhaozg/lua-openssl/issues/)
I try to use [luaunit](https://github.com/bluebird75/luaunit) to write unit
[test](tree/master/test), and welcome PR to improve it.
## Howto
### Howto 1: Build on Linux/Unix System
```bash
git clone --recurse https://github.com/zhaozg/lua-openssl.git lua-openssl
cd lua-openssl
make
make install
make clean
```
If you want to make lua-openssl static link with openssl, please given
`OPENSSL_STATIC` flags, default will do dynamic link.
```bash
make OPENSSL_STATIC=1
```
### Howto 2: Build on Windows with MSVC
Before building, please change the setting in the config.win file.
Works with Lua5.1 (should support Lua5.2 by updating the config.win file).
```bash
git clone --recurse https://github.com/zhaozg/lua-openssl.git lua-openssl
cd lua-openssl
nmake -f makefile.win
nmake -f makefile.win install
nmake -f makefile.win clean
```
### Howto 3: Build on Windows with mingw
```bash
git clone --recurse https://github.com/zhaozg/lua-openssl.git lua-openssl
cd lua-openssl
make
make install
make clean
```
### Howto 4: Install using luarocks
```bash
luarocks install openssl
```
### Howto 5: Build with CMake
Build shared lua-openssl.
`cmake -Bbuild -H. -DOPENSSL_ROOT_DIR=... && cd build && make`
Build static lua-openssl
`cmake -Bbuild -H. -DOPENSSL_ROOT_DIR=... -DBUILD_SHARED_LUA_OPENSSL=OFF && cd build && make`
### Howto 6: Handle fail or error
Most lua-openssl function or methods return nil or false when error or
failed, followed by string type error _reason_ and number type error _code_,
_code_ can pass to openssl.error() to get more error information.
All SSL object IO operation methods return nil or false when fail or error.
When nil returned, it followed by 'ssl' or 'syscall', means SSL layer or
system layer error. When false returned, it is followed by number 0, 'want_read',
'want_write','want_x509_lookup','want_connect','want_accept'. Number 0 means
SSL connection closed, other numbers means you should do some SSL operation.
Please remember that when lua-openssl function or methods fail without an
error code, you can get the last error by openssl.error(), and repeat call
openssl.error() will walk through error stacks of current threads.
openssl.errors() will return all error strings and clear error queue,
this is very useful to free memory when lua-openssl repeat calls or run long times.
## Example usage
### Example 1: short encrypt/decrypt
```lua
local openssl = require('openssl')
local evp_cipher = openssl.cipher.get('aes-128-cbc')
-- Note: Use AES instead of DES as DES is disabled by default in OpenSSL 3.x
local msg = 'abcdefghick'
local key = '1234567890123456' -- 16 bytes for AES-128
local iv = '1234567890123456' -- 16 bytes IV
-- Encrypt with error handling
local cdata, err = evp_cipher:encrypt(msg, key, iv)
if not cdata then
print("Encryption failed: " .. (err or "unknown error"))
return
end
-- Decrypt with error handling
local decrypted, err = evp_cipher:decrypt(cdata, key, iv)
if not decrypted then
print("Decryption failed: " .. (err or "unknown error"))
return
end
assert(msg == decrypted)
```
### Example 2: quick evp_digest
```lua
md = openssl.digest.get('md5')
m = 'abcd'
aa = md:digest(m)
mdc=md:new()
mdc:update(m)
bb = mdc:final()
assert(openssl.hex(aa,true)==bb)
```
### Example 3: Quick HMAC hash
```lua
local hmac = require "openssl".hmac
alg = 'sha256'
key = '0123456789'
msg = 'example message'
hmac.hmac(alg, msg, key, true) -- binary/"raw" output
hmac.hmac(alg, msg, key, false) -- hex output
```
### Example 4: Iterate a openssl.stack_of_x509(sk_x509) object
```lua
n = #sk
for i=1, n do
x = sk:get(i)
end
```
### Example 5: read and parse certificate
```lua
local openssl = require('openssl')
function dump(t,i)
for k,v in pairs(t) do
if(type(v)=='table') then
print( string.rep('\t',i),k..'={')
dump(v,i+1)
print( string.rep('\t',i),k..'=}')
else
print( string.rep('\t',i),k..'='..tostring(v))
end
end
end
function test_x509()
local x = openssl.x509.read(certasstring)
print(x)
t = x:parse()
dump(t,0)
print(t)
end
test_x509()
```
### Example 6: bio network handle(TCP)
- server
```lua
local openssl = require'openssl'
local bio = openssl.bio
host = host or "127.0.0.1"; --only ip
port = port or "8383";
local srv = assert(bio.accept(host..':'..port))
print('listen at:'..port)
local cli = assert(srv:accept())
while 1 do
cli = assert(srv:accept())
print('CLI:',cli)
while cli do
local s = assert(cli:read())
print(s)
assert(cli:write(s))
end
print(openssl.errors())
end
```
- client
```lua
local openssl = require'openssl'
local bio = openssl.bio
io.read()
host = host or "127.0.0.1"; --only ip
port = port or "8383";
local cli = assert(bio.connect(host..':'..port,true))
while cli do
s = io.read()
if(#s>0) then
print(cli:write(s))
ss = cli:read()
assert(#s==#ss)
end
end
print(openssl.errors())
```
### Example 7: SSL client access github.com
```lua
local openssl = require("openssl")
-- prepare a SSL_CTX object
local ctx = assert(openssl.ssl.ctx_new("TLSv1_2_client"))
-- make a TCP connection, and do connect first
local cli = assert(openssl.bio.connect("github:443", true))
-- make a SSL connection over TCP
local ssl = ctx:ssl(cli)
-- set SNI name
ssl:set("hostname", "echo.websocket.org")
-- do SSL handshake
assert(ssl:connect())
-- send a HTTP request over SSL connection
assert(ssl:write("GET / HTTP/1.1\r\nHost: github.com\r\nConnection: close\r\n\r\n"))
-- read response
print(ssl:read(4096))
-- shutdown SSL connection and close TCP connection
ssl:shutdown()
cli:close()
```
### Example 8: aes-128-gcm
```lua
local openssl = require('openssl')
local evp = openssl.cipher.get('aes-128-gcm')
local info = evp:info()
-- get cipher info
local key = openssl.random(info.key_length)
local msg = openssl.random(info.key_length)
local iv = openssl.random(info.iv_length)
local tn = 16 -- tag length
--do encrypt
local e = evp:encrypt_new()
assert(e:ctrl(openssl.cipher.EVP_CTRL_GCM_SET_IVLEN, #iv))
assert(e:init(key, iv))
e:padding(false)
--- get cipher
local c = assert(e:update(msg))
c = c .. e:final()
assert(#c==#msg)
--- Get the tag
local tag = assert(e:ctrl(openssl.cipher.EVP_CTRL_GCM_GET_TAG, tn))
assert(#tag==tn)
--do decrypt
e = evp:decrypt_new()
assert(e:ctrl(openssl.cipher.EVP_CTRL_GCM_SET_IVLEN, #iv))
assert(e:init(key, iv))
e:padding(false)
local r = assert(e:update(c))
assert(e:ctrl(openssl.cipher.EVP_CTRL_GCM_SET_TAG, tag))
r = r .. assert(e:final())
assert(#r==#c)
assert(r==msg)
print('Done')
```
### Example 9: Ed25519 digital signatures
```lua
local openssl = require('openssl')
local pkey = openssl.pkey
-- Generate Ed25519 key pair
local ctx = pkey.ctx_new("ED25519")
local key = ctx:keygen()
-- Sign a message
local message = "Hello, world!"
local signature = pkey.sign(key, message)
-- Verify the signature
local verified = pkey.verify(key, message, signature)
print("Signature verified:", verified) -- true
-- Export and import keys
local pem = key:export("pem")
local imported_key = pkey.read(pem, true, "pem")
print("Key successfully imported")
```
### Example 10: X25519 key exchange
```lua
local openssl = require('openssl')
local pkey = openssl.pkey
-- Alice and Bob each generate a key pair
local alice = pkey.ctx_new("X25519"):keygen()
local bob = pkey.ctx_new("X25519"):keygen()
-- Alice derives shared secret using Bob's public key
local alice_secret = alice:derive(bob)
-- Bob derives shared secret using Alice's public key
local bob_secret = bob:derive(alice)
-- Both secrets should be identical
assert(alice_secret == bob_secret)
print("Shared secret established:", openssl.hex(alice_secret))
```
### Example 11: ChaCha20-Poly1305 AEAD encryption
```lua
local openssl = require('openssl')
local cipher = openssl.cipher
-- Get ChaCha20-Poly1305 cipher
local cc20 = cipher.get("chacha20-poly1305")
-- Prepare key and nonce
local key = string.rep("k", 32) -- 256-bit key
local nonce = string.rep("n", 12) -- 96-bit nonce
local message = "Secret message"
local aad = "Additional authenticated data"
-- Encrypt with AAD
local enc = cc20:encrypt_new()
enc:ctrl(openssl.cipher.EVP_CTRL_GCM_SET_IVLEN, #nonce)
enc:init(key, nonce)
enc:update(aad, true) -- Set AAD
local ciphertext = enc:update(message) .. enc:final()
local tag = enc:ctrl(openssl.cipher.EVP_CTRL_GCM_GET_TAG, 16)
-- Decrypt with AAD
local dec = cc20:decrypt_new()
dec:ctrl(openssl.cipher.EVP_CTRL_GCM_SET_IVLEN, #nonce)
dec:init(key, nonce)
dec:ctrl(openssl.cipher.EVP_CTRL_GCM_SET_TAG, tag)
dec:update(aad, true) -- Set AAD
local plaintext = dec:update(ciphertext) .. dec:final()
assert(plaintext == message)
print("Decrypted:", plaintext)
```
For more examples, please see test lua script files:
- `test/eddsa.lua` - Ed25519/Ed448 digital signatures
- `test/xecdh.lua` - X25519/X448 key exchange
- `test/chacha20.lua` - ChaCha20-Poly1305 AEAD encryption
- `test/2.kdf.lua` - Key derivation functions (PBKDF2, HKDF, SCRYPT)
- `test/2.param.lua` - OSSL_PARAM API usage
---
## Contributing & Community
Contributions via PR or issues are welcome.
- Coding style: please use clang-format.
- Unit tests: recommended [luaunit](https://github.com/bluebird75/luaunit).
- Issue tracker: [GitHub Issues](https://github.com/zhaozg/lua-openssl/issues/)
## Security Notice
This project involves cryptographic algorithms and is intended for learning and research purposes only. Do not use in production for security-sensitive scenarios. Always follow OpenSSL security advisories and keep dependencies up to date.
---
**_lua-openssl License_**
Copyright (c) 2011 - 2026 zhaozg, zhaozg(at)gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---