1 ! Copyright (C) 2017 Alexander Ilin.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: byte-arrays init io.encodings.string io.encodings.utf8
4 kernel math sequences sodium.ffi ;
7 ERROR: sodium-init-fail ;
9 ERROR: buffer-too-small ;
11 ! Call this before any other function, may be called multiple times.
12 : sodium-init ( -- ) sodium_init 0 < [ sodium-init-fail ] when ;
14 : random-bytes ( byte-array -- byte-array' )
15 dup dup length randombytes_buf ;
17 : n-random-bytes ( n -- byte-array )
18 <byte-array> random-bytes ;
20 : check0 ( n -- ) 0 = [ call-fail ] unless ;
22 : crypto-pwhash-str ( password opslimit memlimit -- str )
23 [ crypto_pwhash_strbytes <byte-array> dup ] 3dip
24 [ utf8 encode dup length ] 2dip crypto_pwhash_str check0
27 : crypto-pwhash-str-verify ( str password -- bool )
28 [ utf8 encode ] bi@ dup length crypto_pwhash_str_verify 0 = ;
30 : crypto-generichash ( out-bytes in-bytes key-bytes/f -- out-bytes' )
31 [ dup ] 2dip [ dup length ] tri@ crypto_generichash check0 ;
33 : cipher-buf ( msg-length -- byte-array )
34 crypto_secretbox_macbytes + <byte-array> ;
36 : message-buf ( msg-length -- byte-array )
37 crypto_secretbox_macbytes - <byte-array> ;
39 : check-length ( byte-array min-length -- byte-array )
40 [ dup length ] dip < [ buffer-too-small ] when ;
42 : crypto-secretbox-easy ( msg-bytes nonce-bytes key-bytes -- cipher-bytes )
43 [ dup length [ cipher-buf swap dupd ] keep ]
44 [ crypto_secretbox_noncebytes check-length ]
45 [ crypto_secretbox_keybytes check-length ] tri*
46 crypto_secretbox_easy check0 ;
48 : crypto-secretbox-open-easy ( cipher-bytes nonce-bytes key-bytes -- msg-bytes/f )
50 crypto_secretbox_macbytes check-length
51 dup length [ message-buf swap dupd ] keep
53 [ crypto_secretbox_noncebytes check-length ]
54 [ crypto_secretbox_keybytes check-length ] tri*
55 crypto_secretbox_open_easy 0 = [ drop f ] unless ;
57 [ sodium-init ] "sodium" add-startup-hook