Skip to content

Instantly share code, notes, and snippets.

@catwell
Created August 13, 2017 11:21
Show Gist options
  • Save catwell/ff954569c8d7d08ebcaa107d1fda6304 to your computer and use it in GitHub Desktop.
Save catwell/ff954569c8d7d08ebcaa107d1fda6304 to your computer and use it in GitHub Desktop.
Example of how to use the new box API from PLC
local box = require "box"
-- all keys are 32 bytes long
local f = io.open("/dev/urandom")
-- generate secret keys for Alice and Bob
local sk_a = assert(f:read(32))
local sk_b = assert(f:read(32))
-- deduce the public keys
local pk_a = box.public_key(sk_a)
local pk_b = box.public_key(sk_b)
local plaintext = "Hello Bob, this is Alice!"
-- generate a random 24 bytes nonce
local nonce = f:read(24)
-- encrypt a message from Alice to Bob
local ciphertext = assert(box.box(plaintext, nonce, pk_b, sk_a))
-- there is a 16 bit MAC in front of the message
-- note you must also send the nonce with the message to allow decryption
assert(#ciphertext - #plaintext == 16)
-- Bob decrypts the message from Alice
local decrypted = assert(box.box_open(ciphertext, nonce, pk_a, sk_b))
assert(decrypted == plaintext)
f:close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment