]> gitweb.factorcode.org Git - factor.git/blob - extra/sodium/sodium.factor
sodium: add password hashing 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
10 ! Call this before any other function, may be called multiple times.
11 : sodium-init ( -- ) sodium_init 0 < [ sodium-init-fail ] when ;
12
13 : random-bytes ( byte-array -- byte-array' )
14     dup dup length randombytes_buf ;
15
16 : n-random-bytes ( n -- byte-array )
17     <byte-array> random-bytes ;
18
19 : check0 ( n -- ) 0 = [ call-fail ] unless ;
20
21 : crypto-pwhash-str ( password opslimit memlimit -- str )
22     [ crypto_pwhash_strbytes <byte-array> dup ] 3dip
23     [ utf8 encode dup length ] 2dip crypto_pwhash_str check0
24     utf8 decode ;
25
26 : crypto-pwhash-str-verify ( str password -- bool )
27     [ utf8 encode ] bi@ dup length crypto_pwhash_str_verify 0 = ;
28
29 [ sodium-init ] "sodium" add-startup-hook