Created
February 16, 2020 04:51
-
-
Save christopher-dG/de0a3c86d6683554b1662f7f2f6e933b to your computer and use it in GitHub Desktop.
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
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