From 2f605617a142a93bc2a425c60b247427c009e7fb Mon Sep 17 00:00:00 2001 From: Alexander Iljin Date: Mon, 24 Dec 2018 00:29:39 +0100 Subject: [PATCH] sodium: the add essential crypto-box-* words and a unit-test --- extra/sodium/sodium-tests.factor | 12 ++++++++++++ extra/sodium/sodium.factor | 23 +++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 extra/sodium/sodium-tests.factor diff --git a/extra/sodium/sodium-tests.factor b/extra/sodium/sodium-tests.factor new file mode 100644 index 0000000000..f0d3e38c3a --- /dev/null +++ b/extra/sodium/sodium-tests.factor @@ -0,0 +1,12 @@ +! Copyright (C) 2018 Alexander Ilin. +! See http://factorcode.org/license.txt for BSD license. +USING: arrays io.encodings.string io.encodings.utf8 kernel math +sequences sodium tools.test ; +IN: sodium.tests + +{ t } [ + "Encrypted message" dup utf8 encode + crypto-box-nonce 2 [ crypto-box-keypair 2array ] times + [ [ first ] [ second ] bi* crypto-box-easy ] 3keep swap + [ first ] [ second ] bi* crypto-box-open-easy utf8 decode = +] unit-test diff --git a/extra/sodium/sodium.factor b/extra/sodium/sodium.factor index 95c68f69c4..283e808572 100644 --- a/extra/sodium/sodium.factor +++ b/extra/sodium/sodium.factor @@ -25,6 +25,11 @@ ERROR: buffer-too-small ; : secretbox-message-buf ( cipher-length -- byte-array ) crypto_secretbox_macbytes message-buf ; +: box-cipher-buf ( message-length -- byte-array ) + crypto_box_macbytes cipher-buf ; + +: box-message-buf ( cipher-length -- byte-array ) + crypto_box_macbytes message-buf ; PRIVATE> @@ -65,4 +70,22 @@ PRIVATE> [ crypto_secretbox_keybytes check-length ] tri* crypto_secretbox_open_easy 0 = [ drop f ] unless ; +: crypto-box-keypair ( -- public-key secret-key ) + crypto_box_publickeybytes + crypto_box_secretkeybytes + 2dup crypto_box_keypair check0 ; + +: crypto-box-nonce ( -- nonce-bytes ) + crypto_box_noncebytes n-random-bytes ; + +: crypto-box-easy ( message nonce public-key private-key -- cipher-bytes ) + [ + dup length [ box-cipher-buf dup rot ] keep + ] 3dip crypto_box_easy check0 ; + +: crypto-box-open-easy ( cipher-bytes nonce public-key private-key -- message ) + [ + dup length [ box-message-buf dup rot ] keep + ] 3dip crypto_box_open_easy check0 ; + [ sodium-init ] "sodium" add-startup-hook