]> gitweb.factorcode.org Git - factor.git/commitdiff
sodium: add authenticated encryption and decryption (secretbox) functions
authorAlexander Iljin <ajsoft@yandex.ru>
Thu, 2 Mar 2017 00:37:45 +0000 (03:37 +0300)
committerJohn Benediktsson <mrjbq7@gmail.com>
Mon, 22 Jan 2018 17:26:16 +0000 (09:26 -0800)
extra/sodium/ffi/ffi.factor
extra/sodium/sodium.factor

index 58b5887474f7f6ccc306b21d463d16339d958df3..18ccdd69c600e840abba972e382fef419f3adf1c 100644 (file)
@@ -75,3 +75,23 @@ FUNCTION: int crypto_generichash_update (
     crypto_generichash_state* state, uchar* in, ulonglong inlen )
 FUNCTION: int crypto_generichash_final (
     crypto_generichash_state* state, uchar* out, size_t outlen )
+
+! crypto_secretbox_H
+FUNCTION: size_t crypto_secretbox_keybytes ( )
+FUNCTION: size_t crypto_secretbox_noncebytes ( )
+FUNCTION: size_t crypto_secretbox_macbytes ( )
+FUNCTION: char *crypto_secretbox_primitive ( )
+FUNCTION: int crypto_secretbox_easy (
+    uchar* c, uchar* m, ulonglong mlen,
+    uchar* n, uchar* k )
+FUNCTION: int crypto_secretbox_open_easy (
+    uchar* m, uchar* c, ulonglong clen,
+    uchar* n, uchar* k )
+FUNCTION: int crypto_secretbox_detached (
+    uchar* c, uchar* mac, uchar* m, ulonglong mlen,
+    uchar* n, uchar* k )
+FUNCTION: int crypto_secretbox_open_detached (
+    uchar *m, uchar* c, uchar* mac, ulonglong clen,
+    uchar* n, uchar* k )
+FUNCTION: void crypto_secretbox_keygen (
+    uchar k[crypto_secretbox_KEYBYTES] )
index 490eb8d068d86c25390525b580c7c7aa45411efc..fb1611137312cc5e409f0f9ef8b79839cd02495b 100644 (file)
@@ -6,6 +6,7 @@ IN: sodium
 
 ERROR: sodium-init-fail ;
 ERROR: call-fail ;
+ERROR: buffer-too-small ;
 
 ! Call this before any other function, may be called multiple times.
 : sodium-init ( -- ) sodium_init 0 < [ sodium-init-fail ] when ;
@@ -29,4 +30,28 @@ ERROR: call-fail ;
 : crypto-generichash ( out-bytes in-bytes key-bytes/f -- out-bytes' )
     [ dup ] 2dip [ dup length ] tri@ crypto_generichash check0 ;
 
+: cipher-buf ( msg-length -- byte-array )
+    crypto_secretbox_macbytes + <byte-array> ;
+
+: message-buf ( msg-length -- byte-array )
+    crypto_secretbox_macbytes - <byte-array> ;
+
+: check-length ( byte-array min-length -- byte-array )
+    [ dup length ] dip < [ buffer-too-small ] when ;
+
+: crypto-secretbox-easy ( msg-bytes nonce-bytes key-bytes -- cipher-bytes )
+    [ dup length [ cipher-buf swap dupd ] keep ]
+    [ crypto_secretbox_noncebytes check-length ]
+    [ crypto_secretbox_keybytes check-length ] tri*
+    crypto_secretbox_easy check0 ;
+
+: crypto-secretbox-open-easy ( cipher-bytes nonce-bytes key-bytes -- msg-bytes/f )
+    [
+        crypto_secretbox_macbytes check-length
+        dup length [ message-buf swap dupd ] keep
+    ]
+    [ crypto_secretbox_noncebytes check-length ]
+    [ crypto_secretbox_keybytes check-length ] tri*
+    crypto_secretbox_open_easy 0 = [ drop f ] unless ;
+
 [ sodium-init ] "sodium" add-startup-hook