Skip to content

Instantly share code, notes, and snippets.

@christopher-dG
Created February 16, 2020 04:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christopher-dG/de0a3c86d6683554b1662f7f2f6e933b to your computer and use it in GitHub Desktop.
Save christopher-dG/de0a3c86d6683554b1662f7f2f6e933b to your computer and use it in GitHub Desktop.
module Sodium
export seal
using Base64: base64encode, base64decode
const SEALBYTES = Ref{Csize_t}()
struct SodiumError
fun::Symbol
code::Int
end
Base.showerror(io::IO, e::SodiumError) = print(io, "$(e.fun) returned error code $(e.code)")
macro check(ex::Expr)
fun = ex.args[2].args[1]
return quote
code = $(esc(ex))
code == 0 || throw(SodiumError($fun, code))
end
end
function __init__()
@check ccall((:sodium_init, :libsodium), Cint, ())
SEALBYTES[] = ccall((:crypto_box_sealbytes, :libsodium), Csize_t, ())
end
seal(msg, pk::AbstractString) = base64encode(seal(msg, base64decode(pk)))
function seal(msg, pk)
len = length(msg)
dest = Vector{Cuchar}(undef, SEALBYTES[] + len)
@check ccall(
(:crypto_box_seal, :libsodium),
Cint,
(Ptr{Cuchar}, Ptr{Cuchar}, Culonglong, Ptr{Cuchar}),
pointer(dest), pointer(msg), len, pointer(pk),
)
return dest
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment