Created
November 21, 2016 20:16
-
-
Save FiniteReality/9f40be1867201add04896336a57f5b36 to your computer and use it in GitHub Desktop.
Simple libsodium crypto_secretbox_easy bindings for Lua. Meant for use with discord.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local ffi = require("ffi") | |
-- load libsodium so we can invoke it | |
local sodium = ffi.load("sodium") | |
-- define the headers so we can wrap them | |
ffi.cdef([[ | |
int crypto_secretbox_easy(unsigned char *c, const unsigned char *m, | |
unsigned long long mlen, const unsigned char *n, | |
const unsigned char *k); | |
int crypto_secretbox_open_easy(unsigned char *m, const unsigned char *c, | |
unsigned long long clen, const unsigned char *n, | |
const unsigned char *k); | |
]]) | |
-- encrypts a message with the given nonce and key. | |
-- throws an error when encryption is unsuccessful | |
local function crypto_secretbox_easy(message, nonce, key) | |
assert(#key == 32, "key does not meet size requirement") | |
assert(#nonce == 24, "nonce does not meet size requirement") | |
local mlen = #message | |
local clen = mlen + 16 -- crypto_secretbox_MACBYTES + mlen | |
local c = ffi.new("unsigned char[?]", clen) | |
local s = sodium.crypto_secretbox_easy(c, message, mlen, nonce, key) | |
assert(s == 0, "message encrypted unsuccessfully") | |
return ffi.string(c, clen) | |
end | |
-- decrypts a message with the given nonce and key. | |
-- throws an error when decryption is unsuccessful | |
local function crypto_secretbox_open_easy(ciphertext, nonce, key) | |
assert(#key == 32, "key does not meet size requirement") | |
assert(#nonce == 24, "nonce does not meet size requirement") | |
assert(#ciphertext > 16, "ciphertext does not meet size requirement") | |
local mlen = #ciphertext - 16 | |
local clen = #ciphertext | |
local m = ffi.new("unsigned char[?]", mlen) | |
local s = sodium.crypto_secretbox_open_easy(m, ciphertext, clen, nonce, key) | |
assert(s == 0, "message decrypted unsuccessfully") | |
return ffi.string(m, mlen) | |
end | |
return { | |
encrypt = crypto_secretbox_easy, | |
decrypt = crypto_secretbox_open_easy | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment