]> gitweb.factorcode.org Git - factor.git/blob - extra/sodium/sodium.factor
sodium: move some words into the <PRIVATE> section
[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 <PRIVATE
15
16 : cipher-buf ( message-length n -- byte-array )
17     crypto_secretbox_macbytes + <byte-array> ;
18
19 : message-buf ( cipher-length n -- byte-array )
20     crypto_secretbox_macbytes - <byte-array> ;
21
22 PRIVATE>
23
24 : random-bytes ( byte-array -- byte-array' )
25     dup dup length randombytes_buf ;
26
27 : n-random-bytes ( n -- byte-array )
28     <byte-array> random-bytes ;
29
30 : check0 ( n -- ) 0 = [ call-fail ] unless ;
31
32 : crypto-pwhash-str ( password opslimit memlimit -- str )
33     [ crypto_pwhash_strbytes <byte-array> dup ] 3dip
34     [ utf8 encode dup length ] 2dip crypto_pwhash_str check0
35     utf8 decode ;
36
37 : crypto-pwhash-str-verify ( str password -- bool )
38     [ utf8 encode ] bi@ dup length crypto_pwhash_str_verify 0 = ;
39
40 : crypto-generichash ( out-bytes in-bytes key-bytes/f -- out-bytes' )
41     [ dup ] 2dip [ dup length ] tri@ crypto_generichash check0 ;
42
43 : check-length ( byte-array min-length -- byte-array )
44     [ dup length ] dip < [ buffer-too-small ] when ;
45
46 : crypto-secretbox-easy ( msg-bytes nonce-bytes key-bytes -- cipher-bytes )
47     [ dup length [ cipher-buf swap dupd ] keep ]
48     [ crypto_secretbox_noncebytes check-length ]
49     [ crypto_secretbox_keybytes check-length ] tri*
50     crypto_secretbox_easy check0 ;
51
52 : crypto-secretbox-open-easy ( cipher-bytes nonce-bytes key-bytes -- msg-bytes/f )
53     [
54         crypto_secretbox_macbytes check-length
55         dup length [ message-buf swap dupd ] keep
56     ]
57     [ crypto_secretbox_noncebytes check-length ]
58     [ crypto_secretbox_keybytes check-length ] tri*
59     crypto_secretbox_open_easy 0 = [ drop f ] unless ;
60
61 [ sodium-init ] "sodium" add-startup-hook