]> gitweb.factorcode.org Git - factor.git/blob - extra/sodium/sodium.factor
sodium: add authenticated encryption and decryption (secretbox) functions
[factor.git] / extra / sodium / sodium.factor
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 ;
5 IN: sodium
6
7 ERROR: sodium-init-fail ;
8 ERROR: call-fail ;
9 ERROR: buffer-too-small ;
10
11 ! Call this before any other function, may be called multiple times.
12 : sodium-init ( -- ) sodium_init 0 < [ sodium-init-fail ] when ;
13
14 : random-bytes ( byte-array -- byte-array' )
15     dup dup length randombytes_buf ;
16
17 : n-random-bytes ( n -- byte-array )
18     <byte-array> random-bytes ;
19
20 : check0 ( n -- ) 0 = [ call-fail ] unless ;
21
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
25     utf8 decode ;
26
27 : crypto-pwhash-str-verify ( str password -- bool )
28     [ utf8 encode ] bi@ dup length crypto_pwhash_str_verify 0 = ;
29
30 : crypto-generichash ( out-bytes in-bytes key-bytes/f -- out-bytes' )
31     [ dup ] 2dip [ dup length ] tri@ crypto_generichash check0 ;
32
33 : cipher-buf ( msg-length -- byte-array )
34     crypto_secretbox_macbytes + <byte-array> ;
35
36 : message-buf ( msg-length -- byte-array )
37     crypto_secretbox_macbytes - <byte-array> ;
38
39 : check-length ( byte-array min-length -- byte-array )
40     [ dup length ] dip < [ buffer-too-small ] when ;
41
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 ;
47
48 : crypto-secretbox-open-easy ( cipher-bytes nonce-bytes key-bytes -- msg-bytes/f )
49     [
50         crypto_secretbox_macbytes check-length
51         dup length [ message-buf swap dupd ] keep
52     ]
53     [ crypto_secretbox_noncebytes check-length ]
54     [ crypto_secretbox_keybytes check-length ] tri*
55     crypto_secretbox_open_easy 0 = [ drop f ] unless ;
56
57 [ sodium-init ] "sodium" add-startup-hook