Keys and nonces are types; Argon2id costs are explicit; passwords are NFC

- AeadKey and AeadNonce are opaque types. A key given where a nonce is
  wanted is a type error: for AEGIS-256 both are 32 bytes, and as arrays
  a swap would store the key in clear. Both print as #<AeadKey> and
  #<AeadNonce>.
- A nonce knows its cipher, so aead-encrypt and aead-decrypt take none.
  They and the nonce functions move to (bjosodium raw). (bjosodium core)
  keeps aead-seal and aead-unseal, which make the nonce.
- Every Argon2id function takes an Argon2idCost. There are no defaults:
  a key made with a default that a later version changed would not be
  made again. argon2id-interactive, -moderate and -sensitive are
  libsodium's three costs.
- argon2id-derive-key returns an AeadKey of 32 bytes. #:length is gone.
- Passwords are normalized to Unicode NFC before Argon2id.
- random-bytes. make-aead-key takes no cipher: both keys are 32 bytes.
- (bjosodium impl) holds the code; core and raw are facades of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Linus Björnstam 2026-11-22 08:13:50 +01:00
parent 911f4bcc46
commit 2b42abb6d9
8 changed files with 738 additions and 522 deletions

View file

@ -11,10 +11,12 @@ binding [[https://libsodium.net][LibSodium.Net]].
(defun (main) (defun (main)
;; A key from a password. Store the salt and the cost beside the data. ;; A key from a password. Store the salt and the cost beside the data.
(def salt (make-argon2id-salt)) (def salt (make-argon2id-salt))
(def key (argon2id-derive-key "correct horse" salt)) (def cost argon2id-interactive)
(def key (argon2id-derive-key "correct horse" salt cost))
;; Encrypt. The header is not secret, but a change to it is found. ;; Encrypt. The header is not secret, but a change to it is found. Data
(def cipher (preferred-cipher)) ;; that other devices open must say which cipher it was sealed with.
(def cipher XChaCha20Poly1305)
(def header (string->bytes "bookmarks v1")) (def header (string->bytes "bookmarks v1"))
(def sealed (aead-seal cipher key (string->bytes "https://example.org") #:aad header)) (def sealed (aead-seal cipher key (string->bytes "https://example.org") #:aad header))
@ -29,7 +31,7 @@ binding [[https://libsodium.net][LibSodium.Net]].
(depends (depends
(package (name (bjosodium)) (package (name (bjosodium))
(version (version-at-least "0.1.0")) (version (version-at-least "0.1.0"))
(source (path (dir "../bjosodium"))))) (source (git (url "https://rikspucko.koketteriet.se/bjoli/bjosodium")))))
#+END_SRC #+END_SRC
A program using this package declares no NuGet packages of its own. The A program using this package declares no NuGet packages of its own. The
@ -40,21 +42,49 @@ iOS, tvOS and Mac Catalyst. Nothing has to be installed.
** Operations ** Operations
| ~(aead-encrypt c key nonce data #:aad ad)~ | the ciphertext and the tag; the caller stores the nonce | ~(bjosodium core)~:
| ~(aead-decrypt c key nonce ct #:aad ad)~ | ~(Some data)~, or ~None~ when the tag does not verify |
| ~(make-aead-key)~ | a new random ~AeadKey~ |
| ~(bytes->aead-key bytes)~ ~(aead-key->bytes key)~ | a key from 32 bytes, and a copy of its bytes |
| ~(wipe-aead-key! key)~ | sets the bytes of the key to 0 |
| ~(aead-seal c key data #:aad ad)~ | a new random nonce, the ciphertext and the tag, in one array | | ~(aead-seal c key data #:aad ad)~ | a new random nonce, the ciphertext and the tag, in one array |
| ~(aead-unseal c key sealed #:aad ad)~ | ~(Some data)~, or ~None~ | | ~(aead-unseal c key sealed #:aad ad)~ | ~(Some data)~, or ~None~ when the tag does not verify |
| ~(make-aead-key c)~ ~(make-aead-nonce c)~ | random bytes from the system's random source | | ~(cipher-nonce-length c)~ ~(cipher-tag-length c)~ ~aead-key-length~ | in bytes |
| ~(cipher-key-length c)~ ~(cipher-nonce-length c)~ ~(cipher-tag-length c)~ | in bytes |
| ~(aegis256-accelerated?)~ | true when this CPU runs AEGIS-256 on AES instructions | | ~(aegis256-accelerated?)~ | true when this CPU runs AEGIS-256 on AES instructions |
| ~(preferred-cipher)~ | ~Aegis256~ when it is accelerated, else ~XChaCha20Poly1305~ | | ~(preferred-cipher)~ | ~Aegis256~ when it is accelerated, else ~XChaCha20Poly1305~ |
| ~(argon2id-derive-key pw salt #:iterations #:memory-kib #:length)~ | a key from a password and a 16-byte salt | | ~(make-argon2id-cost t m)~ | an ~Argon2idCost~: ~t~ iterations over ~m~ KiB |
| ~argon2id-interactive~ ~argon2id-moderate~ ~argon2id-sensitive~ | libsodium's three costs |
| ~(argon2id-derive-key pw salt cost)~ | an ~AeadKey~ from a password and a 16-byte salt |
| ~(make-argon2id-salt)~ | 16 random bytes; store them with the data | | ~(make-argon2id-salt)~ | 16 random bytes; store them with the data |
| ~(argon2id-hash pw #:iterations #:memory-kib)~ | a PHC string to store: ~$argon2id$v=19$m=65536,t=2,p=1$...~ | | ~(argon2id-hash pw cost)~ | a PHC string to store: ~$argon2id$v=19$m=65536,t=2,p=1$...~ |
| ~(argon2id-verify pw stored)~ | true when the password gives the stored string | | ~(argon2id-verify pw stored)~ | true when the password gives the stored string |
| ~(argon2id-needs-rehash? stored #:iterations #:memory-kib)~ | true when the stored cost is less than the one given | | ~(argon2id-needs-rehash? stored cost)~ | true when the stored cost is less than ~cost~ |
| ~(random-bytes n)~ | ~n~ bytes from the system's random source |
| ~(wipe! bytes)~ | sets every byte to 0, with ~sodium_memzero~ | | ~(wipe! bytes)~ | sets every byte to 0, with ~sodium_memzero~ |
~(bjosodium raw)~, for a format that stores the nonce in its own place:
| ~(make-aead-nonce c)~ | a new random ~AeadNonce~ of cipher ~c~ |
| ~(bytes->aead-nonce c bytes)~ ~(aead-nonce->bytes n)~ | a nonce read back from stored bytes, and a copy of its bytes |
| ~(aead-encrypt key nonce data #:aad ad)~ | the ciphertext and the tag; the caller stores the nonce |
| ~(aead-decrypt key nonce ct #:aad ad)~ | ~(Some data)~, or ~None~ |
*Keys and nonces are types.* ~AeadKey~ and ~AeadNonce~ are opaque, so a key
given where a nonce is wanted is a type error. For AEGIS-256 both are 32
bytes, and as arrays a swap would not be found: the key would then be stored
in clear beside the data. Both print as ~#<AeadKey>~ and ~#<AeadNonce>~, not
as their bytes. A nonce knows its cipher, so ~aead-encrypt~ and
~aead-decrypt~ take none.
*Costs are explicit.* No Argon2id function has a default cost. A key made
with a default would not be made again if a later version changed the
default, and the data would not open. Store the cost with the data.
*Passwords are normalized to NFC.* A password typed on two devices can come
as different code points: ~é~ as one, or as ~e~ and a combining accent. Both
are normalized to Unicode NFC before Argon2id, so they give the same key. It
is NFC and not NFKC, as in RFC 8265: ~fi~ and ~fi~ are different passwords.
| Cipher | Key | Nonce | Tag | | Cipher | Key | Nonce | Tag |
|---------------------+-----+-------+-----| |---------------------+-----+-------+-----|
| ~Aegis256~ | 32 | 32 | 32 | | ~Aegis256~ | 32 | 32 | 32 |
@ -65,14 +95,16 @@ encrypted, but decryption returns ~None~ when it is not the same as when the
data was encrypted. Use it for a header that must be read before the data is data was encrypted. Use it for a header that must be read before the data is
decrypted, such as a version, a revision or a device id. decrypted, such as a version, a revision or a device id.
*Nonces.* Both ciphers have nonces large enough to be random, so a random *Nonces.* ~aead-seal~ makes a random nonce for each message, which is safe
nonce for each message is safe and there is no counter to keep. Never encrypt with both ciphers: their nonces are large enough to be random, and there is
two messages with the same key and nonce. no counter to keep. With ~(bjosodium raw)~, make each nonce with
~make-aead-nonce~, and never encrypt two messages with the same key and
nonce.
*Errors.* Decryption returns ~None~ when the key, the nonce, the associated *Errors.* Decryption returns ~None~ when the key, the nonce, the associated
data or the bytes are not the ones that were used. A key, a nonce or a salt data or the bytes are not the ones that were used. A key, a nonce or a salt
of the wrong length raises ~ArgumentException~, and so does an Argon2id cost of the wrong length raises ~ArgumentException~, and so does
out of range. ~argon2id-verify~ and ~argon2id-needs-rehash?~ raise ~make-argon2id-cost~ with a cost out of range. ~argon2id-verify~ and ~argon2id-needs-rehash?~ raise
~ArgumentException~ for a stored string that is not an Argon2id PHC string: ~ArgumentException~ for a stored string that is not an Argon2id PHC string:
that is an error in the stored data, not a wrong password. that is an error in the stored data, not a wrong password.
@ -139,8 +171,9 @@ also accepts a string made elsewhere with more lanes.
| Cost | Name in libsodium | Here on a Ryzen 9 5900X | | Cost | Name in libsodium | Here on a Ryzen 9 5900X |
|--------------------------------+-------------------+-------------------------| |--------------------------------+-------------------+-------------------------|
| ~t=2~, ~m=65536~ (64 MiB), the default | INTERACTIVE | 50 ms | | ~t=2~, ~m=65536~ (64 MiB), ~argon2id-interactive~ | INTERACTIVE | 50 ms |
| ~t=3~, ~m=262144~ (256 MiB) | MODERATE | 293 ms | | ~t=3~, ~m=262144~ (256 MiB), ~argon2id-moderate~ | MODERATE | 293 ms |
| ~t=4~, ~m=1048576~ (1 GiB), ~argon2id-sensitive~ | SENSITIVE | not measured |
- A key that unlocks a vault is derived once for each unlock, and an - A key that unlocks a vault is derived once for each unlock, and an
attacker with the stored data can try passwords offline. Choose the attacker with the stored data can try passwords offline. Choose the
@ -150,8 +183,8 @@ also accepts a string made elsewhere with more lanes.
is short of memory. is short of memory.
- Store the salt and the cost with the data, so that a device can derive the - Store the salt and the cost with the data, so that a device can derive the
same key, and so that the cost can increase later. same key, and so that the cost can increase later.
- ~argon2id-derive-key~ takes a salt of exactly 16 bytes, and gives 32 bytes - ~argon2id-derive-key~ takes a salt of exactly 16 bytes, and gives an
unless ~#:length~ says otherwise (at least 16). ~AeadKey~ of 32 bytes.
- The memory is from 8 KiB to 2097151 KiB (just under 2 GiB). - The memory is from 8 KiB to 2097151 KiB (just under 2 GiB).
** Versions ** Versions
@ -174,6 +207,9 @@ LibSodium.Net has more of libsodium than this package exposes: secret streams,
HKDF, public-key encryption, signatures. Add them when they are needed. HKDF, public-key encryption, signatures. Add them when they are needed.
Data goes in and out as arrays, not as spans. Data goes in and out as arrays, not as spans.
~(bjosodium impl)~ is the implementation of both modules. Import ~core~ and
~raw~, not ~impl~.
** Try it ** Try it
#+BEGIN_SRC sh #+BEGIN_SRC sh

View file

@ -14,46 +14,46 @@
(import (std prelude)) (import (std prelude))
(import (std bench)) (import (std bench))
(import (bjosodium core)) (import (bjosodium core))
(import (bjosodium raw))
(def/bench "encrypt AEGIS-256" (def/bench "encrypt AEGIS-256"
#:group "aead" #:group "aead"
#:params ((bytes [1024 1048576])) #:params ((bytes [1024 1048576]))
#:setup ((key (make-aead-key Aegis256)) #:setup ((key (make-aead-key))
(nonce (make-aead-nonce Aegis256)) (nonce (make-aead-nonce Aegis256))
(message (: (make-array bytes) (Array byte)))) (message (: (make-array bytes) (Array byte))))
(aead-encrypt Aegis256 key nonce message)) (aead-encrypt key nonce message))
(def/bench "encrypt XChaCha20-Poly1305" (def/bench "encrypt XChaCha20-Poly1305"
#:group "aead" #:group "aead"
#:params ((bytes [1024 1048576])) #:params ((bytes [1024 1048576]))
#:setup ((key (make-aead-key XChaCha20Poly1305)) #:setup ((key (make-aead-key))
(nonce (make-aead-nonce XChaCha20Poly1305)) (nonce (make-aead-nonce XChaCha20Poly1305))
(message (: (make-array bytes) (Array byte)))) (message (: (make-array bytes) (Array byte))))
(aead-encrypt XChaCha20Poly1305 key nonce message)) (aead-encrypt key nonce message))
(def/bench "decrypt AEGIS-256" (def/bench "decrypt AEGIS-256"
#:group "aead" #:group "aead"
#:params ((bytes [1024 1048576])) #:params ((bytes [1024 1048576]))
#:setup ((key (make-aead-key Aegis256)) #:setup ((key (make-aead-key))
(nonce (make-aead-nonce Aegis256)) (nonce (make-aead-nonce Aegis256))
(boxed (aead-encrypt Aegis256 key nonce (: (make-array bytes) (Array byte))))) (boxed (aead-encrypt key nonce (: (make-array bytes) (Array byte)))))
(aead-decrypt Aegis256 key nonce boxed)) (aead-decrypt key nonce boxed))
(def/bench "decrypt XChaCha20-Poly1305" (def/bench "decrypt XChaCha20-Poly1305"
#:group "aead" #:group "aead"
#:params ((bytes [1024 1048576])) #:params ((bytes [1024 1048576]))
#:setup ((key (make-aead-key XChaCha20Poly1305)) #:setup ((key (make-aead-key))
(nonce (make-aead-nonce XChaCha20Poly1305)) (nonce (make-aead-nonce XChaCha20Poly1305))
(boxed (aead-encrypt XChaCha20Poly1305 key nonce (: (make-array bytes) (Array byte))))) (boxed (aead-encrypt key nonce (: (make-array bytes) (Array byte)))))
(aead-decrypt XChaCha20Poly1305 key nonce boxed)) (aead-decrypt key nonce boxed))
;; The default cost, and libsodium's MODERATE cost. ;; libsodium's INTERACTIVE and MODERATE costs.
(def/bench "argon2id-derive-key" (def/bench "argon2id-derive-key"
#:group "argon2id" #:group "argon2id"
#:params ((cost ["t=2 m=64MiB" "t=3 m=256MiB"])) #:params ((cost ["t=2 m=64MiB" "t=3 m=256MiB"]))
#:setup ((salt (: (make-array argon2id-salt-length) (Array byte))) #:setup ((salt (: (make-array argon2id-salt-length) (Array byte)))
(t (if (= cost "t=2 m=64MiB") 2 3)) (c (if (= cost "t=2 m=64MiB") argon2id-interactive argon2id-moderate)))
(m (if (= cost "t=2 m=64MiB") 65536 262144))) (argon2id-derive-key "correct horse battery staple" salt c))
(argon2id-derive-key "correct horse battery staple" salt #:iterations t #:memory-kib m))
(run-benches) (run-benches)

View file

@ -12,10 +12,12 @@
(defun (main) (defun (main)
;; A key from a password. Store the salt and the cost beside the data. ;; A key from a password. Store the salt and the cost beside the data.
(def salt (make-argon2id-salt)) (def salt (make-argon2id-salt))
(def key (argon2id-derive-key "correct horse" salt)) (def cost argon2id-interactive)
(def key (argon2id-derive-key "correct horse" salt cost))
;; Encrypt. The header is not secret, but a change to it is found. ;; Encrypt. The header is not secret, but a change to it is found. Data
(def cipher (preferred-cipher)) ;; that other devices open must say which cipher it was sealed with.
(def cipher XChaCha20Poly1305)
(def header (string->bytes "bookmarks v1")) (def header (string->bytes "bookmarks v1"))
(def sealed (aead-seal cipher key (string->bytes "https://example.org") #:aad header)) (def sealed (aead-seal cipher key (string->bytes "https://example.org") #:aad header))

View file

@ -1,6 +1,6 @@
(package (package
(name (bjosodium)) (name (bjosodium))
(version "0.1.0") (version "0.2.0")
(description "libsodium for Bjolang: AEGIS-256 and XChaCha20-Poly1305 encryption, and Argon2id password hashing.") (description "libsodium for Bjolang: AEGIS-256 and XChaCha20-Poly1305 encryption, and Argon2id password hashing.")
(license "MPL-2.0") (license "MPL-2.0")

View file

@ -3,432 +3,36 @@
;; file, You can obtain one at http://mozilla.org/MPL/2.0/. ;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;; bjosodium/src/core.bjo — the module (bjosodium core): authenticated ;; bjosodium/src/core.bjo — the module (bjosodium core): authenticated
;; encryption with AEGIS-256 or XChaCha20-Poly1305, and password hashing with ;; encryption with AEGIS-256 or XChaCha20-Poly1305, and keys from passwords
;; Argon2id. The work is done by libsodium, through LibSodium.Net. ;; with Argon2id. The work is done by libsodium, through LibSodium.Net.
;; ;;
;; - Keys, nonces, data and associated data are (Array byte). A password is a ;; - Keys are `AeadKey`, an opaque type. A new one comes from
;; string, used as its UTF-8 bytes. ;; `make-aead-key`, `argon2id-derive-key` or `bytes->aead-key`.
;; - Encryption is AEAD: the result has a tag, and decryption returns `None` ;; - `aead-seal` makes a random nonce and puts it in front of the result.
;; when the tag does not verify. Then the key, the nonce, the associated ;; There is no nonce to choose, so none can be used two times.
;; data or the bytes are not the ones that were used to encrypt. ;; - Every Argon2id function takes its cost as an `Argon2idCost`. There is
;; - `aead-encrypt` takes a nonce from the caller. `aead-seal` makes a random ;; no default: a key made with a default that a later version changes
;; nonce and puts it in front of the result. ;; would not be made again.
;; - Both ciphers have nonces large enough to be random: do not count them. ;; - Passwords are normalized to Unicode NFC.
;; Never encrypt two messages with the same key and nonce. ;;
;; - A wrong length of a key, a nonce or a salt, and a cost out of range, ;; To choose the nonce, as a file format with the nonce in its header does,
;; raise `ArgumentException`. These are errors in the program, not in the ;; import (bjosodium raw) as well.
;; data.
;; - The Argon2id functions take a core for tens to hundreds of milliseconds. (import (bjosodium impl))
;; In a bjoroutine they run on a thread of their own, so the fiber pool is
;; not blocked. (re-export Cipher AeadKey Argon2idCost)
(export (export
;; Ciphers. Transparent: Aegis256, XChaCha20Poly1305. ;; Ciphers
Cipher cipher-key-length cipher-nonce-length cipher-tag-length cipher-nonce-length cipher-tag-length aegis256-accelerated? preferred-cipher
aegis256-accelerated? preferred-cipher ;; Keys
;; Keys and nonces aead-key-length make-aead-key bytes->aead-key aead-key->bytes wipe-aead-key!
make-aead-key make-aead-nonce
;; Encryption ;; Encryption
aead-encrypt aead-decrypt aead-seal aead-unseal aead-seal aead-unseal
;; Argon2id ;; Argon2id
make-argon2id-cost argon2id-cost-iterations argon2id-cost-memory-kib
argon2id-interactive argon2id-moderate argon2id-sensitive
argon2id-derive-key argon2id-hash argon2id-verify argon2id-needs-rehash? argon2id-derive-key argon2id-hash argon2id-verify argon2id-needs-rehash?
make-argon2id-salt argon2id-salt-length default-argon2id-iterations default-argon2id-memory-kib make-argon2id-salt argon2id-salt-length
;; Memory ;; Random bytes and memory
wipe!) random-bytes wipe!)
(import (std prelude))
(type (: Cipher (Union Aegis256 XChaCha20Poly1305)))
(import/class
(ArgumentException (: System.ArgumentException (-> string ArgumentException)))
(Algorithm (: LibSodium.PasswordHashArgonAlgorithm)))
;; LibSodium.Net's AEAD methods take the output, the input, the key, the tag,
;; the associated data and the nonce, in that order. A tag span makes the
;; call detached: the tag goes into that span. Each method returns the part
;; of the output it wrote, which this module does not need.
;;
;; An empty span for the tag or the nonce is not the same as no argument, so
;; every call gives all six.
(import/extern
(clr-aegis-encrypt (: LibSodium.Aegis256.Encrypt
(-> (Span byte) (RoSpan byte) (RoSpan byte) (Span byte) (RoSpan byte) (RoSpan byte)
(Span byte))))
;; Raises `LibSodiumException` when the tag does not verify.
(clr-aegis-decrypt (: LibSodium.Aegis256.Decrypt
(-> (Span byte) (RoSpan byte) (RoSpan byte) (RoSpan byte) (RoSpan byte) (RoSpan byte)
(Span byte))))
(clr-xchacha-encrypt (: LibSodium.XChaCha20Poly1305.Encrypt
(-> (Span byte) (RoSpan byte) (RoSpan byte) (Span byte) (RoSpan byte) (RoSpan byte)
(Span byte))))
;; Raises `LibSodiumException` when the tag does not verify.
(clr-xchacha-decrypt (: LibSodium.XChaCha20Poly1305.Decrypt
(-> (Span byte) (RoSpan byte) (RoSpan byte) (RoSpan byte) (RoSpan byte) (RoSpan byte)
(Span byte))))
;; libsodium's randombytes_buf: the system's random source.
(clr-random-fill (: LibSodium.RandomGenerator.Fill (-> (Span byte) void)))
;; sodium_memzero.
(clr-mem-zero (: LibSodium.SecureMemory.MemZero (-> (Array byte) void)))
;; The key, the password, the salt, the iterations, the memory in bytes,
;; and the algorithm.
(clr-argon2-derive (: LibSodium.CryptoPasswordHashArgon.DeriveKey
(-> (Span byte) (RoSpan byte) (RoSpan byte) int int Algorithm void)))
;; The password, the iterations and the memory in bytes. Argon2id, with a
;; random salt.
(clr-argon2-hash (: LibSodium.CryptoPasswordHashArgon.HashPassword (-> (RoSpan byte) int int string)))
(clr-argon2-verify (: LibSodium.CryptoPasswordHashArgon.VerifyPassword (-> string (RoSpan byte) bool)))
(clr-arm-aes? (: System.Runtime.Intrinsics.Arm.Aes.IsSupported #:get))
(clr-x86-aes? (: System.Runtime.Intrinsics.X86.Aes.IsSupported #:get))
(clr-x86-avx? (: System.Runtime.Intrinsics.X86.Avx.IsSupported #:get)))
(: (-> string %a))
(defun (refuse message) (raise (cast Exception (ArgumentException. message))))
;; ---------------------------------------------------------------------------
;; Ciphers
;; ---------------------------------------------------------------------------
;; In bytes.
(: (-> Cipher int))
(defun (cipher-key-length cipher)
(match cipher
(Aegis256 32)
(XChaCha20Poly1305 32)))
;; In bytes.
(: (-> Cipher int))
(defun (cipher-nonce-length cipher)
(match cipher
(Aegis256 32)
(XChaCha20Poly1305 24)))
;; In bytes. The ciphertext is this much longer than the plaintext.
(: (-> Cipher int))
(defun (cipher-tag-length cipher)
(match cipher
(Aegis256 32)
(XChaCha20Poly1305 16)))
;; libsodium uses AES instructions for AEGIS-256 when the CPU has them: the
;; ARMv8 AES instructions on 64-bit ARM, or AES-NI and AVX on x86. Without
;; them it uses AES in software, which is slower than XChaCha20-Poly1305.
;; This is the same test, as .NET reports the CPU.
(: (-> bool))
(defun (aegis256-accelerated?)
(or clr-arm-aes? (and clr-x86-aes? clr-x86-avx?)))
;; Aegis256 when `aegis256-accelerated?`, else XChaCha20Poly1305. Both are
;; safe; this is the faster one on this CPU.
(: (-> Cipher))
(defun (preferred-cipher)
(if (aegis256-accelerated?) Aegis256 XChaCha20Poly1305))
(: (-> Cipher string))
(defun (cipher-label cipher)
(match cipher
(Aegis256 "AEGIS-256")
(XChaCha20Poly1305 "XChaCha20-Poly1305")))
(: (-> Cipher string (Array byte) int void))
(defun (check-length! cipher what bytes wanted)
(def n (array-length bytes))
(when (not (= n wanted))
(refuse (str "The " what " of " (cipher-label cipher) " must be " (int->string wanted)
" bytes, not " (int->string n) "."))))
(: (-> Cipher (Array byte) void))
(defun (check-key! cipher key) (check-length! cipher "key" key (cipher-key-length cipher)))
(: (-> Cipher (Array byte) void))
(defun (check-nonce! cipher nonce) (check-length! cipher "nonce" nonce (cipher-nonce-length cipher)))
;; ---------------------------------------------------------------------------
;; Keys and nonces
;; ---------------------------------------------------------------------------
(: (-> int (Array byte)))
(defun (random-array n)
(def bytes (: (make-array n) (Array byte)))
(clr-random-fill (array->span bytes))
bytes)
;; A new random key, from the system's random source.
(: (-> Cipher (Array byte)))
(defun (make-aead-key cipher) (random-array (cipher-key-length cipher)))
;; A new random nonce, from the system's random source.
(: (-> Cipher (Array byte)))
(defun (make-aead-nonce cipher) (random-array (cipher-nonce-length cipher)))
;; ---------------------------------------------------------------------------
;; Encryption
;; ---------------------------------------------------------------------------
(: (Array byte))
(def no-aad (make-array 0))
;; Writes the ciphertext of `plaintext` into `out`, then the tag. `out` is
;; exactly as long as the two. The caller checks the key and the nonce.
(: (-> Cipher (RoSpan byte) (RoSpan byte) (RoSpan byte) (RoSpan byte) (Span byte) void))
(defun (encrypt-into! cipher key nonce aad plaintext out)
(def n (ro-span-length plaintext))
(def text (span-slice out #:to n))
(def tag (span-slice out #:from n))
(ignore
(match cipher
(Aegis256 (span-length (clr-aegis-encrypt text plaintext key tag aad nonce)))
(XChaCha20Poly1305 (span-length (clr-xchacha-encrypt text plaintext key tag aad nonce))))))
;; The plaintext of the bytes of `box` from `from`: the ciphertext, then the
;; tag. The caller checks the key, the nonce, and that the tag fits.
;; Raises `LibSodiumException` when the tag does not verify.
(: (-> Cipher (Array byte) (Array byte) (Array byte) (Array byte) int (Array byte)))
(defun (decrypt-now cipher key nonce aad box from)
(def n (- (array-length box) from (cipher-tag-length cipher)))
(def out (: (make-array n) (Array byte)))
(def text (array->ro-span box #:from from #:to (+ from n)))
(def tag (array->ro-span box #:from (+ from n)))
(def k (array->ro-span key))
(def a (array->ro-span aad))
(def iv (array->ro-span nonce))
(ignore
(match cipher
(Aegis256 (span-length (clr-aegis-decrypt (array->span out) text k tag a iv)))
(XChaCha20Poly1305 (span-length (clr-xchacha-decrypt (array->span out) text k tag a iv)))))
out)
;; `decrypt-now`, with `None` when the tag does not verify.
(: (-> Cipher (Array byte) (Array byte) (Array byte) (Array byte) int (Option (Array byte))))
(defun (decrypt-checked cipher key nonce aad box from)
(match (try (decrypt-now cipher key nonce aad box from) #:catch (LibSodium.LibSodiumException))
((Ok plaintext) (Some plaintext))
((Err _) None)))
;; The ciphertext and then the tag: `cipher-tag-length` bytes longer than
;; `plaintext`. The nonce is not in the result; store it beside it.
(: (-> Cipher (Array byte) (Array byte) (Array byte) (#:aad (Array byte)) (Array byte)))
(defun (aead-encrypt cipher key nonce plaintext #:aad no-aad)
(check-key! cipher key)
(check-nonce! cipher nonce)
(def out (: (make-array (+ (array-length plaintext) (cipher-tag-length cipher))) (Array byte)))
(encrypt-into! cipher (array->ro-span key) (array->ro-span nonce) (array->ro-span aad)
(array->ro-span plaintext) (array->span out))
out)
;; The plaintext of a result of `aead-encrypt`. `None` when the tag does not
;; verify, and when `ciphertext` is shorter than a tag.
(: (-> Cipher (Array byte) (Array byte) (Array byte) (#:aad (Array byte)) (Option (Array byte))))
(defun (aead-decrypt cipher key nonce ciphertext #:aad no-aad)
(check-key! cipher key)
(check-nonce! cipher nonce)
(if (< (array-length ciphertext) (cipher-tag-length cipher))
None
(decrypt-checked cipher key nonce aad ciphertext 0)))
;; A new random nonce, the ciphertext, and the tag, in one array.
(: (-> Cipher (Array byte) (Array byte) (#:aad (Array byte)) (Array byte)))
(defun (aead-seal cipher key plaintext #:aad no-aad)
(check-key! cipher key)
(def nonce-length (cipher-nonce-length cipher))
(def out (: (make-array (+ nonce-length (array-length plaintext) (cipher-tag-length cipher)))
(Array byte)))
(clr-random-fill (array->span out #:to nonce-length))
(encrypt-into! cipher (array->ro-span key) (array->ro-span out #:to nonce-length)
(array->ro-span aad) (array->ro-span plaintext) (array->span out #:from nonce-length))
out)
;; The plaintext of a result of `aead-seal`. `None` when the tag does not
;; verify, and when `sealed` is shorter than a nonce and a tag.
(: (-> Cipher (Array byte) (Array byte) (#:aad (Array byte)) (Option (Array byte))))
(defun (aead-unseal cipher key sealed #:aad no-aad)
(check-key! cipher key)
(def nonce-length (cipher-nonce-length cipher))
(if (< (array-length sealed) (+ nonce-length (cipher-tag-length cipher)))
None
(decrypt-checked cipher key (ro-span->array (array->ro-span sealed #:to nonce-length)) aad
sealed nonce-length)))
;; ---------------------------------------------------------------------------
;; Argon2id
;; ---------------------------------------------------------------------------
;;
;; libsodium's Argon2id is version 1.3 with one lane (p=1). The cost is the
;; number of iterations (t) and the memory in KiB (m).
;; In bytes: crypto_pwhash_SALTBYTES.
(: int)
(def argon2id-salt-length 16)
;; A new random salt for `argon2id-derive-key`, from the system's random
;; source. A salt need not be secret: store it with the data.
(: (-> (Array byte)))
(defun (make-argon2id-salt) (random-array argon2id-salt-length))
;; libsodium's OPSLIMIT_INTERACTIVE and MEMLIMIT_INTERACTIVE: 2 iterations
;; over 64 MiB.
(: int)
(def default-argon2id-iterations 2)
(: int)
(def default-argon2id-memory-kib 65536)
;; crypto_pwhash_BYTES_MIN.
(: int)
(def min-key-length 16)
;; crypto_pwhash_MEMLIMIT_MIN is 8 KiB. LibSodium.Net takes the memory in
;; bytes as an int, so the most it can give is just under 2 GiB.
(: int)
(def min-memory-kib 8)
(: int)
(def max-memory-kib 2097151)
(: (-> int int void))
(defun (check-cost! iterations memory-kib)
(when (< iterations 1)
(refuse (str "The iteration count must be at least 1, not " (int->string iterations) ".")))
(when (or (< memory-kib min-memory-kib) (> memory-kib max-memory-kib))
(refuse (str "The memory must be from " (int->string min-memory-kib) " to "
(int->string max-memory-kib) " KiB, not " (int->string memory-kib) "."))))
;; The value of a thread's result, or its exception raised again.
(: (-> (Result Exception %a) %a))
(defun (unwrap-thread r)
(match r
((Ok v) v)
((Err e) (raise e))))
(: (-> string (Array byte) int int int (Array byte)))
(defun (derive-now password salt iterations memory-kib length)
(check-cost! iterations memory-kib)
(when (< length min-key-length)
(refuse (str "The key length must be at least " (int->string min-key-length) " bytes, not "
(int->string length) ".")))
(when (not (= (array-length salt) argon2id-salt-length))
(refuse (str "The salt must be " (int->string argon2id-salt-length) " bytes, not "
(int->string (array-length salt)) ".")))
(def key (: (make-array length) (Array byte)))
(def secret (string->bytes password))
(try (clr-argon2-derive (array->span key) (array->ro-span secret) (array->ro-span salt)
iterations (* memory-kib 1024) Algorithm.Argon2id13)
#:finally (clr-mem-zero secret))
key)
(: (-> string int int string))
(defun (hash-now password iterations memory-kib)
(check-cost! iterations memory-kib)
(def secret (string->bytes password))
(try (clr-argon2-hash (array->ro-span secret) iterations (* memory-kib 1024))
#:finally (clr-mem-zero secret)))
;; What a stored hash says about its cost.
(type (: Argon2Cost (Record (: cost-memory-kib int)
(: cost-iterations int)
(: cost-lanes int))))
;; ASCII digits, as an int. `None` for an empty string, for any other
;; character, and for a number too big for an int.
(: (-> string (Option int)))
(defun (decimal text)
(def bytes (string->bytes text))
(def n (array-length bytes))
(let go ((i 0) (v 0L))
(cond
((= i n) (if (> n 0) (Some (cast int v)) None))
(else
(def b (cast int (array-ref bytes i)))
(def next (+ (* v 10L) (cast long (- b 48))))
(if (and (>= b 48) (<= b 57) (<= next 2147483647L))
(go (+ i 1) next)
None)))))
;; The number after `prefix` in `field`, as `m=65536`.
(: (-> string string (Option int)))
(defun (field-value field prefix)
(if (string-starts-with? field prefix)
(decimal (string-drop field (string-length prefix)))
None))
;; Raises `ArgumentException` when `stored` is not
;; `$argon2id$v=19$m=<n>,t=<n>,p=<n>$<salt>$<hash>`. The salt and the hash
;; must not be empty. Their base64 is checked by libsodium.
(: (-> string Argon2Cost))
(defun (parse-stored stored)
(def fail "Not an Argon2id hash: expected $argon2id$v=19$m=<n>,t=<n>,p=<n>$<salt>$<hash>.")
(def parts (string-split stored "$"))
;; The leading `$` makes the first part empty.
(if (not (and (= (vec-length parts) 6)
(= (vec-ref parts 0) "")
(= (vec-ref parts 1) "argon2id")
(= (vec-ref parts 2) "v=19")
(> (string-length (vec-ref parts 4)) 0)
(> (string-length (vec-ref parts 5)) 0)))
(refuse fail)
(let ((fields (string-split (vec-ref parts 3) ",")))
(if (not (= (vec-length fields) 3))
(refuse fail)
(match (Tuple (field-value (vec-ref fields 0) "m=")
(field-value (vec-ref fields 1) "t=")
(field-value (vec-ref fields 2) "p="))
((Tuple (Some m) (Some t) (Some p))
(Argon2Cost (cost-memory-kib m) (cost-iterations t) (cost-lanes p)))
(_ (refuse fail)))))))
(: (-> string string bool))
(defun (verify-now password stored)
(ignore (parse-stored stored))
(def secret (string->bytes password))
(try (clr-argon2-verify stored (array->ro-span secret))
#:finally (clr-mem-zero secret)))
;; Argon2id bytes of `password` with the salt given: the same password, salt
;; and cost give the same bytes. Use it to make a key from a password.
;; Raises `ArgumentException` when the salt is not `argon2id-salt-length`
;; bytes, the length is less than 16, or the cost is out of range.
(: (-> string (Array byte) (#:iterations int) (#:memory-kib int) (#:length int) (Array byte)))
(defbjouble (argon2id-derive-key password salt #:iterations default-argon2id-iterations
#:memory-kib default-argon2id-memory-kib #:length 32)
(#:sync (derive-now password salt iterations memory-kib length))
(#:bjo (unwrap-thread
(sync (spawn/thread #(derive-now password salt iterations memory-kib length))))))
;; A PHC string to store: `$argon2id$v=19$m=65536,t=2,p=1$<salt>$<hash>`,
;; with a random salt of 16 bytes and a hash of 32. Raises
;; `ArgumentException` when the cost is out of range.
(: (-> string (#:iterations int) (#:memory-kib int) string))
(defbjouble (argon2id-hash password #:iterations default-argon2id-iterations
#:memory-kib default-argon2id-memory-kib)
(#:sync (hash-now password iterations memory-kib))
(#:bjo (unwrap-thread (sync (spawn/thread #(hash-now password iterations memory-kib))))))
;; True when `password` gives `stored`. The cost comes from `stored`.
;; Raises `ArgumentException` when `stored` is not an Argon2id PHC string.
;; This is an error in the stored data, not a wrong password.
(: (-> string string bool))
(defbjouble (argon2id-verify password stored)
(#:sync (verify-now password stored))
(#:bjo (unwrap-thread (sync (spawn/thread #(verify-now password stored))))))
;; True when `stored` was made with fewer iterations or less memory than
;; given. Check this after a correct `argon2id-verify`, and store a new hash
;; of the password if it is true. Raises `ArgumentException` when `stored` is
;; not an Argon2id PHC string.
(: (-> string (#:iterations int) (#:memory-kib int) bool))
(defun (argon2id-needs-rehash? stored #:iterations default-argon2id-iterations
#:memory-kib default-argon2id-memory-kib)
(def cost (parse-stored stored))
(or (< (record-ref cost cost-iterations) iterations)
(< (record-ref cost cost-memory-kib) memory-kib)))
;; ---------------------------------------------------------------------------
;; Memory
;; ---------------------------------------------------------------------------
;; Sets every byte of `bytes` to 0, with sodium_memzero, which the compiler
;; does not remove. Use it on a key when you no longer need it. The garbage
;; collector can have moved the array before, and it does not clear the old
;; copy, so this makes copies fewer but does not remove all of them.
(: (-> (Array byte) void))
(defun (wipe! bytes) (clr-mem-zero bytes))

497
src/impl.bjo Normal file
View file

@ -0,0 +1,497 @@
;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;; bjosodium/src/impl.bjo — the module (bjosodium impl): the implementation
;; of (bjosodium core) and (bjosodium raw). Import those, not this module.
;;
;; - Keys and nonces are opaque types, `AeadKey` and `AeadNonce`, so that one
;; cannot be given where the other is wanted. Data, associated data and
;; salts are (Array byte).
;; - A password is a string. It is normalized to Unicode NFC, then used as
;; its UTF-8 bytes.
;; - Encryption is AEAD: decryption returns `None` when the tag does not
;; verify. Then the key, the nonce, the associated data or the bytes are
;; not the ones that were used to encrypt.
;; - A wrong length of a key, a nonce or a salt, and a cost out of range,
;; raise `ArgumentException`. These are errors in the program, not in the
;; data.
;; - The Argon2id functions take a core for tens to hundreds of milliseconds.
;; In a bjoroutine they run on a thread of their own, so the fiber pool is
;; not blocked.
(export
;; Ciphers. Transparent: Aegis256, XChaCha20Poly1305.
Cipher cipher-nonce-length cipher-tag-length
aegis256-accelerated? preferred-cipher
;; Keys
AeadKey aead-key-length make-aead-key bytes->aead-key aead-key->bytes wipe-aead-key!
;; Sealing: a random nonce in front of the result
aead-seal aead-unseal
;; Nonces and encryption with them, for (bjosodium raw)
AeadNonce make-aead-nonce bytes->aead-nonce aead-nonce->bytes aead-nonce-cipher
aead-encrypt aead-decrypt
;; Argon2id
Argon2idCost make-argon2id-cost argon2id-cost-iterations argon2id-cost-memory-kib
argon2id-interactive argon2id-moderate argon2id-sensitive
argon2id-derive-key argon2id-hash argon2id-verify argon2id-needs-rehash?
make-argon2id-salt argon2id-salt-length
;; Random bytes and memory
random-bytes wipe!)
(import (std prelude))
(type (: Cipher (Union Aegis256 XChaCha20Poly1305)))
(import/class
(ArgumentException (: System.ArgumentException (-> string ArgumentException)))
(Algorithm (: LibSodium.PasswordHashArgonAlgorithm)))
;; LibSodium.Net's AEAD methods take the output, the input, the key, the tag,
;; the associated data and the nonce, in that order. A tag span makes the
;; call detached: the tag goes into that span. Each method returns the part
;; of the output it wrote, which this module does not need.
;;
;; An empty span for the tag or the nonce is not the same as no argument, so
;; every call gives all six.
(import/extern
(clr-aegis-encrypt (: LibSodium.Aegis256.Encrypt
(-> (Span byte) (RoSpan byte) (RoSpan byte) (Span byte) (RoSpan byte) (RoSpan byte)
(Span byte))))
;; Raises `LibSodiumException` when the tag does not verify.
(clr-aegis-decrypt (: LibSodium.Aegis256.Decrypt
(-> (Span byte) (RoSpan byte) (RoSpan byte) (RoSpan byte) (RoSpan byte) (RoSpan byte)
(Span byte))))
(clr-xchacha-encrypt (: LibSodium.XChaCha20Poly1305.Encrypt
(-> (Span byte) (RoSpan byte) (RoSpan byte) (Span byte) (RoSpan byte) (RoSpan byte)
(Span byte))))
;; Raises `LibSodiumException` when the tag does not verify.
(clr-xchacha-decrypt (: LibSodium.XChaCha20Poly1305.Decrypt
(-> (Span byte) (RoSpan byte) (RoSpan byte) (RoSpan byte) (RoSpan byte) (RoSpan byte)
(Span byte))))
;; libsodium's randombytes_buf: the system's random source.
(clr-random-fill (: LibSodium.RandomGenerator.Fill (-> (Span byte) void)))
;; sodium_memzero.
(clr-mem-zero (: LibSodium.SecureMemory.MemZero (-> (Array byte) void)))
;; The key, the password, the salt, the iterations, the memory in bytes,
;; and the algorithm.
(clr-argon2-derive (: LibSodium.CryptoPasswordHashArgon.DeriveKey
(-> (Span byte) (RoSpan byte) (RoSpan byte) int int Algorithm void)))
;; The password, the iterations and the memory in bytes. Argon2id, with a
;; random salt.
(clr-argon2-hash (: LibSodium.CryptoPasswordHashArgon.HashPassword (-> (RoSpan byte) int int string)))
(clr-argon2-verify (: LibSodium.CryptoPasswordHashArgon.VerifyPassword (-> string (RoSpan byte) bool)))
;; String.Normalize() with no argument: Unicode normalization form C.
(clr-nfc (: System.String.Normalize (-> string string)))
(clr-arm-aes? (: System.Runtime.Intrinsics.Arm.Aes.IsSupported #:get))
(clr-x86-aes? (: System.Runtime.Intrinsics.X86.Aes.IsSupported #:get))
(clr-x86-avx? (: System.Runtime.Intrinsics.X86.Avx.IsSupported #:get)))
(: (-> string %a))
(defun (refuse message) (raise (cast Exception (ArgumentException. message))))
(: (-> (Array byte) (Array byte)))
(defun (copy-of bytes) (ro-span->array (array->ro-span bytes)))
;; ---------------------------------------------------------------------------
;; Ciphers
;; ---------------------------------------------------------------------------
;; In bytes.
(: (-> Cipher int))
(defun (cipher-nonce-length cipher)
(match cipher
(Aegis256 32)
(XChaCha20Poly1305 24)))
;; In bytes. The ciphertext is this much longer than the plaintext.
(: (-> Cipher int))
(defun (cipher-tag-length cipher)
(match cipher
(Aegis256 32)
(XChaCha20Poly1305 16)))
;; libsodium uses AES instructions for AEGIS-256 when the CPU has them: the
;; ARMv8 AES instructions on 64-bit ARM, or AES-NI and AVX on x86. Without
;; them it uses AES in software, which is slower than XChaCha20-Poly1305.
;; This is the same test, as .NET reports the CPU.
(: (-> bool))
(defun (aegis256-accelerated?)
(or clr-arm-aes? (and clr-x86-aes? clr-x86-avx?)))
;; Aegis256 when `aegis256-accelerated?`, else XChaCha20Poly1305. Both are
;; safe; this is the faster one on this CPU.
(: (-> Cipher))
(defun (preferred-cipher)
(if (aegis256-accelerated?) Aegis256 XChaCha20Poly1305))
(: (-> Cipher string))
(defun (cipher-label cipher)
(match cipher
(Aegis256 "AEGIS-256")
(XChaCha20Poly1305 "XChaCha20-Poly1305")))
;; ---------------------------------------------------------------------------
;; Random bytes and memory
;; ---------------------------------------------------------------------------
;; `n` bytes from the system's random source.
(: (-> int (Array byte)))
(defun (random-bytes n)
(when (< n 0) (refuse (str "The number of random bytes must be at least 0, not " (int->string n) ".")))
(def bytes (: (make-array n) (Array byte)))
(clr-random-fill (array->span bytes))
bytes)
;; Sets every byte of `bytes` to 0, with sodium_memzero, which the compiler
;; does not remove. The garbage collector can have moved the array before,
;; and it does not clear the old copy, so this makes copies fewer but does
;; not remove all of them.
(: (-> (Array byte) void))
(defun (wipe! bytes) (clr-mem-zero bytes))
;; ---------------------------------------------------------------------------
;; Keys
;; ---------------------------------------------------------------------------
;; A key of either cipher: 32 bytes. Opaque, and printed as #<AeadKey>, so
;; that its bytes do not get into a log.
(type (: AeadKey #:opaque (Record (: key-bytes (Array byte)))))
;; In bytes, for both ciphers.
(: int)
(def aead-key-length 32)
;; A new random key, from the system's random source.
(: (-> AeadKey))
(defun (make-aead-key) (AeadKey (key-bytes (random-bytes aead-key-length))))
;; A key from a copy of `bytes`, as `aead-key->bytes` gave them. Raises
;; `ArgumentException` when `bytes` is not `aead-key-length` bytes.
(: (-> (Array byte) AeadKey))
(defun (bytes->aead-key bytes)
(def n (array-length bytes))
(when (not (= n aead-key-length))
(refuse (str "A key must be " (int->string aead-key-length) " bytes, not " (int->string n) ".")))
(AeadKey (key-bytes (copy-of bytes))))
;; A copy of the bytes of `key`, to encrypt it with another key or to store
;; it. Wipe the copy with `wipe!` when it is no longer needed.
(: (-> AeadKey (Array byte)))
(defun (aead-key->bytes key) (copy-of (record-ref key key-bytes)))
;; Sets the bytes of `key` to 0. The key must not be used after this: it
;; would encrypt with a key of zeros.
(: (-> AeadKey void))
(defun (wipe-aead-key! key) (wipe! (record-ref key key-bytes)))
;; ---------------------------------------------------------------------------
;; Nonces
;; ---------------------------------------------------------------------------
;; A nonce of one cipher. Opaque. It knows its cipher, so `aead-encrypt`
;; and `aead-decrypt` take no cipher.
(type (: AeadNonce #:opaque (Record (: nonce-cipher Cipher)
(: nonce-bytes (Array byte)))))
;; A new random nonce for `cipher`, from the system's random source.
(: (-> Cipher AeadNonce))
(defun (make-aead-nonce cipher)
(AeadNonce (nonce-cipher cipher) (nonce-bytes (random-bytes (cipher-nonce-length cipher)))))
;; A nonce of `cipher` from a copy of `bytes`, as `aead-nonce->bytes` gave
;; them. Raises `ArgumentException` when `bytes` is not the cipher's nonce
;; length.
(: (-> Cipher (Array byte) AeadNonce))
(defun (bytes->aead-nonce cipher bytes)
(def n (array-length bytes))
(def wanted (cipher-nonce-length cipher))
(when (not (= n wanted))
(refuse (str "The nonce of " (cipher-label cipher) " must be " (int->string wanted)
" bytes, not " (int->string n) ".")))
(AeadNonce (nonce-cipher cipher) (nonce-bytes (copy-of bytes))))
;; A copy of the bytes of `nonce`, to store beside the ciphertext.
(: (-> AeadNonce (Array byte)))
(defun (aead-nonce->bytes nonce) (copy-of (record-ref nonce nonce-bytes)))
(: (-> AeadNonce Cipher))
(defun (aead-nonce-cipher nonce) (record-ref nonce nonce-cipher))
;; ---------------------------------------------------------------------------
;; Encryption
;; ---------------------------------------------------------------------------
(: (Array byte))
(def no-aad (make-array 0))
;; Writes the ciphertext of `plaintext` into `out`, then the tag. `out` is
;; exactly as long as the two.
(: (-> Cipher (RoSpan byte) (RoSpan byte) (RoSpan byte) (RoSpan byte) (Span byte) void))
(defun (encrypt-into! cipher key nonce aad plaintext out)
(def n (ro-span-length plaintext))
(def text (span-slice out #:to n))
(def tag (span-slice out #:from n))
(ignore
(match cipher
(Aegis256 (span-length (clr-aegis-encrypt text plaintext key tag aad nonce)))
(XChaCha20Poly1305 (span-length (clr-xchacha-encrypt text plaintext key tag aad nonce))))))
;; The plaintext of the bytes of `box` from `from`: the ciphertext, then the
;; tag. The caller checks that the tag fits.
;; Raises `LibSodiumException` when the tag does not verify.
(: (-> Cipher (RoSpan byte) (RoSpan byte) (Array byte) (Array byte) int (Array byte)))
(defun (decrypt-now cipher key nonce aad box from)
(def n (- (array-length box) from (cipher-tag-length cipher)))
(def out (: (make-array n) (Array byte)))
(def text (array->ro-span box #:from from #:to (+ from n)))
(def tag (array->ro-span box #:from (+ from n)))
(def a (array->ro-span aad))
(ignore
(match cipher
(Aegis256 (span-length (clr-aegis-decrypt (array->span out) text key tag a nonce)))
(XChaCha20Poly1305 (span-length (clr-xchacha-decrypt (array->span out) text key tag a nonce)))))
out)
;; `decrypt-now`, with `None` when the tag does not verify.
(: (-> Cipher (RoSpan byte) (RoSpan byte) (Array byte) (Array byte) int (Option (Array byte))))
(defun (decrypt-checked cipher key nonce aad box from)
(match (try (decrypt-now cipher key nonce aad box from) #:catch (LibSodium.LibSodiumException))
((Ok plaintext) (Some plaintext))
((Err _) None)))
(: (-> AeadKey (RoSpan byte)))
(defun (key-span key) (array->ro-span (record-ref key key-bytes)))
;; The ciphertext and then the tag: `cipher-tag-length` bytes longer than
;; `plaintext`. The nonce is not in the result; store it beside it. Never
;; encrypt two messages with the same key and nonce.
(: (-> AeadKey AeadNonce (Array byte) (#:aad (Array byte)) (Array byte)))
(defun (aead-encrypt key nonce plaintext #:aad no-aad)
(def cipher (record-ref nonce nonce-cipher))
(def out (: (make-array (+ (array-length plaintext) (cipher-tag-length cipher))) (Array byte)))
(encrypt-into! cipher (key-span key) (array->ro-span (record-ref nonce nonce-bytes)) (array->ro-span aad)
(array->ro-span plaintext) (array->span out))
out)
;; The plaintext of a result of `aead-encrypt`. `None` when the tag does not
;; verify, and when `ciphertext` is shorter than a tag.
(: (-> AeadKey AeadNonce (Array byte) (#:aad (Array byte)) (Option (Array byte))))
(defun (aead-decrypt key nonce ciphertext #:aad no-aad)
(def cipher (record-ref nonce nonce-cipher))
(if (< (array-length ciphertext) (cipher-tag-length cipher))
None
(decrypt-checked cipher (key-span key) (array->ro-span (record-ref nonce nonce-bytes)) aad ciphertext 0)))
;; A new random nonce, the ciphertext, and the tag, in one array:
;; `cipher-nonce-length` and `cipher-tag-length` bytes longer than
;; `plaintext`. The cipher is not in the result: store it beside it, or use
;; one cipher everywhere.
(: (-> Cipher AeadKey (Array byte) (#:aad (Array byte)) (Array byte)))
(defun (aead-seal cipher key plaintext #:aad no-aad)
(def nonce-length (cipher-nonce-length cipher))
(def out (: (make-array (+ nonce-length (array-length plaintext) (cipher-tag-length cipher)))
(Array byte)))
(clr-random-fill (array->span out #:to nonce-length))
(encrypt-into! cipher (key-span key) (array->ro-span out #:to nonce-length)
(array->ro-span aad) (array->ro-span plaintext) (array->span out #:from nonce-length))
out)
;; The plaintext of a result of `aead-seal` with the same cipher. `None` when
;; the tag does not verify, and when `sealed` is shorter than a nonce and a
;; tag.
(: (-> Cipher AeadKey (Array byte) (#:aad (Array byte)) (Option (Array byte))))
(defun (aead-unseal cipher key sealed #:aad no-aad)
(def nonce-length (cipher-nonce-length cipher))
(if (< (array-length sealed) (+ nonce-length (cipher-tag-length cipher)))
None
(decrypt-checked cipher (key-span key) (array->ro-span sealed #:to nonce-length) aad
sealed nonce-length)))
;; ---------------------------------------------------------------------------
;; Argon2id
;; ---------------------------------------------------------------------------
;;
;; libsodium's Argon2id is version 1.3 with one lane (p=1). The cost is the
;; number of iterations (t) and the memory in KiB (m).
;; In bytes: crypto_pwhash_SALTBYTES.
(: int)
(def argon2id-salt-length 16)
;; A new random salt for `argon2id-derive-key`, from the system's random
;; source. A salt need not be secret: store it with the data.
(: (-> (Array byte)))
(defun (make-argon2id-salt) (random-bytes argon2id-salt-length))
;; crypto_pwhash_MEMLIMIT_MIN is 8 KiB. LibSodium.Net takes the memory in
;; bytes as an int, so the most it can give is just under 2 GiB.
(: int)
(def min-memory-kib 8)
(: int)
(def max-memory-kib 2097151)
;; A cost of Argon2id: the iterations and the memory in KiB. Opaque, so that
;; each one was checked by `make-argon2id-cost`.
(type (: Argon2idCost #:opaque (Record (: cost-iterations int)
(: cost-memory-kib int))))
;; Raises `ArgumentException` when `iterations` is less than 1, or
;; `memory-kib` is not from 8 to 2097151.
(: (-> int int Argon2idCost))
(defun (make-argon2id-cost iterations memory-kib)
(when (< iterations 1)
(refuse (str "The iteration count must be at least 1, not " (int->string iterations) ".")))
(when (or (< memory-kib min-memory-kib) (> memory-kib max-memory-kib))
(refuse (str "The memory must be from " (int->string min-memory-kib) " to "
(int->string max-memory-kib) " KiB, not " (int->string memory-kib) ".")))
(Argon2idCost (cost-iterations iterations) (cost-memory-kib memory-kib)))
(: (-> Argon2idCost int))
(defun (argon2id-cost-iterations cost) (record-ref cost cost-iterations))
(: (-> Argon2idCost int))
(defun (argon2id-cost-memory-kib cost) (record-ref cost cost-memory-kib))
;; libsodium's OPSLIMIT_INTERACTIVE and MEMLIMIT_INTERACTIVE: 2 iterations
;; over 64 MiB.
(: Argon2idCost)
(def argon2id-interactive (make-argon2id-cost 2 65536))
;; libsodium's MODERATE: 3 iterations over 256 MiB.
(: Argon2idCost)
(def argon2id-moderate (make-argon2id-cost 3 262144))
;; libsodium's SENSITIVE: 4 iterations over 1 GiB.
(: Argon2idCost)
(def argon2id-sensitive (make-argon2id-cost 4 1048576))
;; The UTF-8 bytes of `password` in Unicode NFC. The same password typed on
;; two devices can come as different code points: "é" as one, or as "e" and
;; a combining accent. NFC makes them the same bytes.
(: (-> string (Array byte)))
(defun (password-bytes password) (string->bytes (clr-nfc password)))
;; The value of a thread's result, or its exception raised again.
(: (-> (Result Exception %a) %a))
(defun (unwrap-thread r)
(match r
((Ok v) v)
((Err e) (raise e))))
(: (-> string (Array byte) Argon2idCost AeadKey))
(defun (derive-now password salt cost)
(when (not (= (array-length salt) argon2id-salt-length))
(refuse (str "The salt must be " (int->string argon2id-salt-length) " bytes, not "
(int->string (array-length salt)) ".")))
(def key (: (make-array aead-key-length) (Array byte)))
(def secret (password-bytes password))
(try (clr-argon2-derive (array->span key) (array->ro-span secret) (array->ro-span salt)
(argon2id-cost-iterations cost) (* (argon2id-cost-memory-kib cost) 1024)
Algorithm.Argon2id13)
#:finally (clr-mem-zero secret))
(AeadKey (key-bytes key)))
(: (-> string Argon2idCost string))
(defun (hash-now password cost)
(def secret (password-bytes password))
(try (clr-argon2-hash (array->ro-span secret) (argon2id-cost-iterations cost)
(* (argon2id-cost-memory-kib cost) 1024))
#:finally (clr-mem-zero secret)))
;; What a stored hash says about its cost.
(type (: StoredCost (Record (: stored-memory-kib int)
(: stored-iterations int)
(: stored-lanes int))))
;; ASCII digits, as an int. `None` for an empty string, for any other
;; character, and for a number too big for an int.
(: (-> string (Option int)))
(defun (decimal text)
(def bytes (string->bytes text))
(def n (array-length bytes))
(let go ((i 0) (v 0L))
(cond
((= i n) (if (> n 0) (Some (cast int v)) None))
(else
(def b (cast int (array-ref bytes i)))
(def next (+ (* v 10L) (cast long (- b 48))))
(if (and (>= b 48) (<= b 57) (<= next 2147483647L))
(go (+ i 1) next)
None)))))
;; The number after `prefix` in `field`, as `m=65536`.
(: (-> string string (Option int)))
(defun (field-value field prefix)
(if (string-starts-with? field prefix)
(decimal (string-drop field (string-length prefix)))
None))
;; Raises `ArgumentException` when `stored` is not
;; `$argon2id$v=19$m=<n>,t=<n>,p=<n>$<salt>$<hash>`. The salt and the hash
;; must not be empty. Their base64 is checked by libsodium.
(: (-> string StoredCost))
(defun (parse-stored stored)
(def fail "Not an Argon2id hash: expected $argon2id$v=19$m=<n>,t=<n>,p=<n>$<salt>$<hash>.")
(def parts (string-split stored "$"))
;; The leading `$` makes the first part empty.
(if (not (and (= (vec-length parts) 6)
(= (vec-ref parts 0) "")
(= (vec-ref parts 1) "argon2id")
(= (vec-ref parts 2) "v=19")
(> (string-length (vec-ref parts 4)) 0)
(> (string-length (vec-ref parts 5)) 0)))
(refuse fail)
(let ((fields (string-split (vec-ref parts 3) ",")))
(if (not (= (vec-length fields) 3))
(refuse fail)
(match (Tuple (field-value (vec-ref fields 0) "m=")
(field-value (vec-ref fields 1) "t=")
(field-value (vec-ref fields 2) "p="))
((Tuple (Some m) (Some t) (Some p))
(StoredCost (stored-memory-kib m) (stored-iterations t) (stored-lanes p)))
(_ (refuse fail)))))))
(: (-> string string bool))
(defun (verify-now password stored)
(ignore (parse-stored stored))
(def secret (password-bytes password))
(try (clr-argon2-verify stored (array->ro-span secret))
#:finally (clr-mem-zero secret)))
;; A key from `password` and `salt`: the same password, salt and cost give
;; the same key. Store the salt and the cost with the data, to derive the
;; key again.
;; Raises `ArgumentException` when the salt is not `argon2id-salt-length`
;; bytes.
(: (-> string (Array byte) Argon2idCost AeadKey))
(defbjouble (argon2id-derive-key password salt cost)
(#:sync (derive-now password salt cost))
(#:bjo (unwrap-thread (sync (spawn/thread #(derive-now password salt cost))))))
;; A PHC string to store: `$argon2id$v=19$m=65536,t=2,p=1$<salt>$<hash>`,
;; with a random salt of 16 bytes and a hash of 32. The cost is in the
;; string.
(: (-> string Argon2idCost string))
(defbjouble (argon2id-hash password cost)
(#:sync (hash-now password cost))
(#:bjo (unwrap-thread (sync (spawn/thread #(hash-now password cost))))))
;; True when `password` gives `stored`. The cost comes from `stored`.
;; Raises `ArgumentException` when `stored` is not an Argon2id PHC string.
;; This is an error in the stored data, not a wrong password.
(: (-> string string bool))
(defbjouble (argon2id-verify password stored)
(#:sync (verify-now password stored))
(#:bjo (unwrap-thread (sync (spawn/thread #(verify-now password stored))))))
;; True when `stored` was made with fewer iterations or less memory than
;; `cost`. Check this after a correct `argon2id-verify`, and store a new hash
;; of the password if it is true. Raises `ArgumentException` when `stored` is
;; not an Argon2id PHC string.
(: (-> string Argon2idCost bool))
(defun (argon2id-needs-rehash? stored cost)
(def found (parse-stored stored))
(or (< (record-ref found stored-iterations) (argon2id-cost-iterations cost))
(< (record-ref found stored-memory-kib) (argon2id-cost-memory-kib cost))))

23
src/raw.bjo Normal file
View file

@ -0,0 +1,23 @@
;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;; bjosodium/src/raw.bjo — the module (bjosodium raw): encryption with a
;; nonce that the caller gives, for a format that keeps the nonce in its own
;; place. Use it with (bjosodium core), which has the keys.
;;
;; - A nonce is `AeadNonce`, an opaque type that knows its cipher.
;; `aead-encrypt` and `aead-decrypt` take the cipher from it.
;; - Make each nonce with `make-aead-nonce`. Never encrypt two messages with
;; the same key and nonce: that shows the XOR of the two plaintexts, and
;; lets an attacker forge messages.
;; - `bytes->aead-nonce` is for a nonce read back from stored data, to
;; decrypt. Do not encrypt with a nonce made from bytes.
(import (bjosodium impl))
(re-export AeadNonce)
(export
make-aead-nonce bytes->aead-nonce aead-nonce->bytes aead-nonce-cipher
aead-encrypt aead-decrypt)

View file

@ -2,8 +2,9 @@
;; License, v. 2.0. If a copy of the MPL was not distributed with this ;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/. ;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;; bjosodium/tests/core.bjo — (bjosodium core) against libsodium's own test ;; bjosodium/tests/core.bjo — (bjosodium core) and (bjosodium raw) against
;; vectors, and the failures that must give `None` or raise. ;; libsodium's own test vectors, and the failures that must give `None` or
;; raise.
;; ;;
;; bjo run tests/core.bjo ;; bjo run tests/core.bjo
;; ;;
@ -24,6 +25,7 @@
(import (std simpletest)) (import (std simpletest))
(import (std crypto hash)) (import (std crypto hash))
(import (bjosodium core)) (import (bjosodium core))
(import (bjosodium raw))
(import/class (import/class
(ArgumentException (: System.ArgumentException (-> string ArgumentException)))) (ArgumentException (: System.ArgumentException (-> string ArgumentException))))
@ -56,16 +58,22 @@
(: (-> (Array byte) int (Array byte))) (: (-> (Array byte) int (Array byte)))
(defun (first-bytes bytes n) (ro-span->array (array->ro-span bytes #:to n))) (defun (first-bytes bytes n) (ro-span->array (array->ro-span bytes #:to n)))
(: (-> AeadKey string))
(defun (key-hex key) (bytes->hex (aead-key->bytes key)))
(: Argon2idCost)
(def cheap (make-argon2id-cost 1 8192))
;; The non-bjoroutine versions, called from `main` through these. ;; The non-bjoroutine versions, called from `main` through these.
(: (-> string (Array byte) int int (Array byte))) (: (-> string (Array byte) int int string))
(defun (derive/sync password salt t m) (defun (derive/sync password salt t m)
(argon2id-derive-key password salt #:iterations t #:memory-kib m)) (key-hex (argon2id-derive-key password salt (make-argon2id-cost t m))))
(: (-> string string bool)) (: (-> string string bool))
(defun (verify/sync password stored) (argon2id-verify password stored)) (defun (verify/sync password stored) (argon2id-verify password stored))
(: (-> string string)) (: (-> string string))
(defun (hash/sync password) (argon2id-hash password #:iterations 1 #:memory-kib 8192)) (defun (hash/sync password) (argon2id-hash password cheap))
;; ---- Vectors ---------------------------------------------------------------- ;; ---- Vectors ----------------------------------------------------------------
@ -105,37 +113,47 @@
(: (-> Cipher void)) (: (-> Cipher void))
(defun (check-cipher cipher) (defun (check-cipher cipher)
(def name (written cipher)) (def name (written cipher))
(def key (make-aead-key cipher)) (def key (make-aead-key))
(def nonce (make-aead-nonce cipher)) (def nonce (make-aead-nonce cipher))
(def aad (string->bytes "header, revision 7")) (def aad (string->bytes "header, revision 7"))
(def message (string->bytes "https://example.org/ — a bookmark")) (def message (string->bytes "https://example.org/ — a bookmark"))
(def boxed (aead-encrypt cipher key nonce message #:aad aad)) (def boxed (aead-encrypt key nonce message #:aad aad))
(def tag-length (cipher-tag-length cipher)) (def tag-length (cipher-tag-length cipher))
(expect #"${name}: a new nonce has the cipher's length" (array-length (aead-nonce->bytes nonce))
(cipher-nonce-length cipher))
(expect #"${name}: a nonce knows its cipher" (aead-nonce-cipher nonce) cipher)
(expect #"${name}: the ciphertext is a tag longer" (array-length boxed) (expect #"${name}: the ciphertext is a tag longer" (array-length boxed)
(+ (array-length message) tag-length)) (+ (array-length message) tag-length))
(expect #"${name}: round trip" (opened (aead-decrypt cipher key nonce boxed #:aad aad)) (expect #"${name}: round trip" (opened (aead-decrypt key nonce boxed #:aad aad))
(bytes->hex message)) (bytes->hex message))
(expect #"${name}: a changed ciphertext byte" (opened (aead-decrypt cipher key nonce (flipped boxed 0) #:aad aad)) (expect #"${name}: a changed ciphertext byte" (opened (aead-decrypt key nonce (flipped boxed 0) #:aad aad))
"None") "None")
(expect #"${name}: a changed tag byte" (expect #"${name}: a changed tag byte"
(opened (aead-decrypt cipher key nonce (flipped boxed (- (array-length boxed) 1)) #:aad aad)) (opened (aead-decrypt key nonce (flipped boxed (- (array-length boxed) 1)) #:aad aad))
"None") "None")
(expect #"${name}: another key" (opened (aead-decrypt cipher (make-aead-key cipher) nonce boxed #:aad aad)) (expect #"${name}: another key" (opened (aead-decrypt (make-aead-key) nonce boxed #:aad aad))
"None") "None")
(expect #"${name}: another nonce" (opened (aead-decrypt cipher key (flipped nonce 3) boxed #:aad aad)) (expect #"${name}: another nonce"
(opened (aead-decrypt key (bytes->aead-nonce cipher (flipped (aead-nonce->bytes nonce) 3)) boxed #:aad aad))
"None") "None")
(expect #"${name}: the nonce read back from its bytes"
(opened (aead-decrypt key (bytes->aead-nonce cipher (aead-nonce->bytes nonce)) boxed #:aad aad))
(bytes->hex message))
(expect #"${name}: the key read back from its bytes"
(opened (aead-decrypt (bytes->aead-key (aead-key->bytes key)) nonce boxed #:aad aad))
(bytes->hex message))
(expect #"${name}: other associated data" (expect #"${name}: other associated data"
(opened (aead-decrypt cipher key nonce boxed #:aad (string->bytes "header, revision 6"))) (opened (aead-decrypt key nonce boxed #:aad (string->bytes "header, revision 6")))
"None") "None")
(expect #"${name}: no associated data" (opened (aead-decrypt cipher key nonce boxed)) "None") (expect #"${name}: no associated data" (opened (aead-decrypt key nonce boxed)) "None")
(expect #"${name}: cut short" (opened (aead-decrypt cipher key nonce (first-bytes boxed (- (array-length boxed) 1)) #:aad aad)) (expect #"${name}: cut short" (opened (aead-decrypt key nonce (first-bytes boxed (- (array-length boxed) 1)) #:aad aad))
"None") "None")
(expect #"${name}: shorter than a tag" (opened (aead-decrypt cipher key nonce (first-bytes boxed (- tag-length 1)) #:aad aad)) (expect #"${name}: shorter than a tag" (opened (aead-decrypt key nonce (first-bytes boxed (- tag-length 1)) #:aad aad))
"None") "None")
;; The empty message: only the tag. ;; The empty message: only the tag.
(def empty (aead-encrypt cipher key nonce (make-array 0))) (def empty (aead-encrypt key nonce (make-array 0)))
(expect #"${name}: an empty message is a tag" (array-length empty) tag-length) (expect #"${name}: an empty message is a tag" (array-length empty) tag-length)
(expect #"${name}: an empty message opens" (opened (aead-decrypt cipher key nonce empty)) "") (expect #"${name}: an empty message opens" (opened (aead-decrypt key nonce empty)) "")
;; Sealed: a new nonce in front. ;; Sealed: a new nonce in front.
(def sealed (aead-seal cipher key message #:aad aad)) (def sealed (aead-seal cipher key message #:aad aad))
(expect #"${name}: sealed is a nonce and a tag longer" (array-length sealed) (expect #"${name}: sealed is a nonce and a tag longer" (array-length sealed)
@ -153,44 +171,59 @@
(def sealed-empty (aead-seal cipher key (make-array 0))) (def sealed-empty (aead-seal cipher key (make-array 0)))
(expect #"${name}: an empty message sealed" (opened (aead-unseal cipher key sealed-empty)) "") (expect #"${name}: an empty message sealed" (opened (aead-unseal cipher key sealed-empty)) "")
;; Wrong lengths are errors in the program. ;; Wrong lengths are errors in the program.
(expect #"${name}: a short key raises" (raises? #(aead-encrypt cipher (make-array 16) nonce message)) #t) (expect #"${name}: a nonce from too few bytes raises" (raises? #(bytes->aead-nonce cipher (make-array 12))) #t)
(expect #"${name}: a short nonce raises" (raises? #(aead-encrypt cipher key (make-array 12) message)) #t) (expect #"${name}: a nonce from too many bytes raises" (raises? #(bytes->aead-nonce cipher (make-array 40))) #t))
(expect #"${name}: decrypt with a short key raises" (raises? #(aead-decrypt cipher (make-array 16) nonce boxed)) #t)
(expect #"${name}: decrypt with a long nonce raises" (raises? #(aead-decrypt cipher key (make-array 40) boxed)) #t)
(expect #"${name}: seal with a short key raises" (raises? #(aead-seal cipher (make-array 31) message)) #t)
(expect #"${name}: unseal with a short key raises" (raises? #(aead-unseal cipher (make-array 31) sealed)) #t))
(defbjo (main args) (defbjo (main args)
;; ---- Lengths -------------------------------------------------------------- ;; ---- Lengths --------------------------------------------------------------
(expect "AEGIS-256 key" (cipher-key-length Aegis256) 32) (expect "a key" aead-key-length 32)
(expect "AEGIS-256 nonce" (cipher-nonce-length Aegis256) 32) (expect "AEGIS-256 nonce" (cipher-nonce-length Aegis256) 32)
(expect "AEGIS-256 tag" (cipher-tag-length Aegis256) 32) (expect "AEGIS-256 tag" (cipher-tag-length Aegis256) 32)
(expect "XChaCha20-Poly1305 key" (cipher-key-length XChaCha20Poly1305) 32)
(expect "XChaCha20-Poly1305 nonce" (cipher-nonce-length XChaCha20Poly1305) 24) (expect "XChaCha20-Poly1305 nonce" (cipher-nonce-length XChaCha20Poly1305) 24)
(expect "XChaCha20-Poly1305 tag" (cipher-tag-length XChaCha20Poly1305) 16) (expect "XChaCha20-Poly1305 tag" (cipher-tag-length XChaCha20Poly1305) 16)
(expect "a key has the key length" (array-length (make-aead-key XChaCha20Poly1305)) 32) (expect "a new key has the key length" (array-length (aead-key->bytes (make-aead-key))) 32)
(expect "a nonce has the nonce length" (array-length (make-aead-nonce XChaCha20Poly1305)) 24) (expect-true "two keys differ" (not (= (key-hex (make-aead-key)) (key-hex (make-aead-key)))))
(expect-true "two keys differ"
(not (= (bytes->hex (make-aead-key Aegis256)) (bytes->hex (make-aead-key Aegis256)))))
(expect "the preferred cipher follows the CPU" (preferred-cipher) (expect "the preferred cipher follows the CPU" (preferred-cipher)
(if (aegis256-accelerated?) Aegis256 XChaCha20Poly1305)) (if (aegis256-accelerated?) Aegis256 XChaCha20Poly1305))
(println #"note: aegis256-accelerated? is ${(written (aegis256-accelerated?))} here") (println #"note: aegis256-accelerated? is ${(written (aegis256-accelerated?))} here")
;; ---- Keys -----------------------------------------------------------------
(def bytes32 (random-bytes 32))
(expect "a key from bytes has them" (key-hex (bytes->aead-key bytes32)) (bytes->hex bytes32))
(def from-bytes (bytes->aead-key bytes32))
(wipe! bytes32)
(expect-true "a key from bytes is a copy of them" (not (= (key-hex from-bytes) (bytes->hex bytes32))))
(def out (aead-key->bytes from-bytes))
(wipe! out)
(expect-true "the bytes of a key are a copy" (not (= (key-hex from-bytes) (bytes->hex out))))
(expect "a key from 31 bytes raises" (raises? #(bytes->aead-key (make-array 31))) #t)
(expect "a key from 33 bytes raises" (raises? #(bytes->aead-key (make-array 33))) #t)
(expect "a key is not printed" (displayed (make-aead-key)) "#<AeadKey>")
(expect "a nonce is not printed" (displayed (make-aead-nonce Aegis256)) "#<AeadNonce>")
(def wiped (make-aead-key))
(wipe-aead-key! wiped)
(expect "wipe-aead-key! clears every byte" (key-hex wiped) (bytes->hex (make-array 32)))
;; ---- Known answers -------------------------------------------------------- ;; ---- Known answers --------------------------------------------------------
(expect "AEGIS-256 vector" (bytes->hex (aead-encrypt Aegis256 aegis-key aegis-nonce aegis-message #:aad aegis-ad)) (def aegis (bytes->aead-nonce Aegis256 aegis-nonce))
(expect "AEGIS-256 vector"
(bytes->hex (aead-encrypt (bytes->aead-key aegis-key) aegis aegis-message #:aad aegis-ad))
(str aegis-ciphertext aegis-tag)) (str aegis-ciphertext aegis-tag))
(expect "AEGIS-256 vector decrypts" (expect "AEGIS-256 vector decrypts"
(opened (aead-decrypt Aegis256 aegis-key aegis-nonce (unhex (str aegis-ciphertext aegis-tag)) #:aad aegis-ad)) (opened (aead-decrypt (bytes->aead-key aegis-key) aegis (unhex (str aegis-ciphertext aegis-tag))
#:aad aegis-ad))
(bytes->hex aegis-message)) (bytes->hex aegis-message))
(def xchacha (bytes->aead-nonce XChaCha20Poly1305 xchacha-nonce))
(expect "XChaCha20-Poly1305 vector" (expect "XChaCha20-Poly1305 vector"
(bytes->hex (aead-encrypt XChaCha20Poly1305 xchacha-key xchacha-nonce xchacha-message #:aad xchacha-ad)) (bytes->hex (aead-encrypt (bytes->aead-key xchacha-key) xchacha xchacha-message #:aad xchacha-ad))
(str xchacha-ciphertext xchacha-tag)) (str xchacha-ciphertext xchacha-tag))
(expect "XChaCha20-Poly1305 vector decrypts" (expect "XChaCha20-Poly1305 vector decrypts"
(opened (aead-decrypt XChaCha20Poly1305 xchacha-key xchacha-nonce (opened (aead-decrypt (bytes->aead-key xchacha-key) xchacha
(unhex (str xchacha-ciphertext xchacha-tag)) #:aad xchacha-ad)) (unhex (str xchacha-ciphertext xchacha-tag)) #:aad xchacha-ad))
(bytes->hex xchacha-message)) (bytes->hex xchacha-message))
(expect "a ciphertext of one cipher does not open with the other" (expect "a ciphertext of one cipher does not open with the other"
(opened (aead-decrypt XChaCha20Poly1305 aegis-key (first-bytes aegis-nonce 24) (opened (aead-decrypt (bytes->aead-key aegis-key)
(bytes->aead-nonce XChaCha20Poly1305 (first-bytes aegis-nonce 24))
(unhex (str aegis-ciphertext aegis-tag)) #:aad aegis-ad)) (unhex (str aegis-ciphertext aegis-tag)) #:aad aegis-ad))
"None") "None")
@ -198,16 +231,29 @@
(check-cipher Aegis256) (check-cipher Aegis256)
(check-cipher XChaCha20Poly1305) (check-cipher XChaCha20Poly1305)
;; ---- Argon2id: costs ------------------------------------------------------
(expect "interactive" (Tuple (argon2id-cost-iterations argon2id-interactive)
(argon2id-cost-memory-kib argon2id-interactive))
(Tuple 2 65536))
(expect "moderate" (Tuple (argon2id-cost-iterations argon2id-moderate) (argon2id-cost-memory-kib argon2id-moderate))
(Tuple 3 262144))
(expect "sensitive" (Tuple (argon2id-cost-iterations argon2id-sensitive)
(argon2id-cost-memory-kib argon2id-sensitive))
(Tuple 4 1048576))
(expect "no iterations" (raises? #(make-argon2id-cost 0 4096)) #t)
(expect "too little memory" (raises? #(make-argon2id-cost 1 7)) #t)
(expect "too much memory" (raises? #(make-argon2id-cost 1 2097152)) #t)
(expect "the smallest cost" (argon2id-cost-memory-kib (make-argon2id-cost 1 8)) 8)
;; ---- Argon2id: known answers ---------------------------------------------- ;; ---- Argon2id: known answers ----------------------------------------------
(def salt-4 (string->bytes ">A 16-bytes salt"))
(expect "derive: tv3 entry 4" (expect "derive: tv3 entry 4"
(bytes->hex (argon2id-derive-key argon-password-4 (string->bytes ">A 16-bytes salt") (key-hex (argon2id-derive-key argon-password-4 salt-4 (make-argon2id-cost 19 4096)))
#:iterations 19 #:memory-kib 4096))
argon-hash-4) argon-hash-4)
(expect "derive: tv3 entry 4, from a plain function" (expect "derive: tv3 entry 4, from a plain function" (derive/sync argon-password-4 salt-4 19 4096)
(bytes->hex (derive/sync argon-password-4 (string->bytes ">A 16-bytes salt") 19 4096))
argon-hash-4) argon-hash-4)
(expect "derive: tv3 entry 2, the empty password" (expect "derive: tv3 entry 2, the empty password"
(bytes->hex (argon2id-derive-key "" argon-salt-2 #:iterations 2 #:memory-kib 4882)) (key-hex (argon2id-derive-key "" argon-salt-2 (make-argon2id-cost 2 4882)))
argon-hash-2) argon-hash-2)
(expect "verify: tv3 entry 4" (argon2id-verify argon-password-4 argon-stored-4) #t) (expect "verify: tv3 entry 4" (argon2id-verify argon-password-4 argon-stored-4) #t)
(expect "verify: tv3 entry 4, from a plain function" (verify/sync argon-password-4 argon-stored-4) #t) (expect "verify: tv3 entry 4, from a plain function" (verify/sync argon-password-4 argon-stored-4) #t)
@ -229,21 +275,34 @@
"$argon2id$v=19$m=4096,t=18,p=1$PkEgMTYtYnl0ZXMgc2FsdA$ltB/ue1kPtBMBGfsysMpPigE6hiNEKZ9vs8vLNVDQGA") "$argon2id$v=19$m=4096,t=18,p=1$PkEgMTYtYnl0ZXMgc2FsdA$ltB/ue1kPtBMBGfsysMpPigE6hiNEKZ9vs8vLNVDQGA")
#f) #f)
;; ---- Argon2id: Unicode NFC ------------------------------------------------
;; "é" as one code point, U+00E9, and as "e" and U+0301.
(def composed "caf\u{E9}")
(def decomposed "cafe\u{301}")
(expect-true "the two forms are different strings" (not (= composed decomposed)))
(expect "derive: the two forms give one key"
(key-hex (argon2id-derive-key decomposed salt-4 cheap))
(key-hex (argon2id-derive-key composed salt-4 cheap)))
(expect "verify: a hash of one form verifies the other" (argon2id-verify decomposed (hash/sync composed)) #t)
(expect "derive: NFC, not NFKC: the ligature fi is not fi"
(= (key-hex (argon2id-derive-key "\u{FB01}" salt-4 cheap)) (key-hex (argon2id-derive-key "fi" salt-4 cheap)))
#f)
;; ---- Argon2id: hash and verify -------------------------------------------- ;; ---- Argon2id: hash and verify --------------------------------------------
(def stored (argon2id-hash "correct horse" #:iterations 1 #:memory-kib 8192)) (def stored (argon2id-hash "correct horse" cheap))
(expect-true "a hash is a PHC string with its cost" (string-starts-with? stored "$argon2id$v=19$m=8192,t=1,p=1$")) (expect-true "a hash is a PHC string with its cost" (string-starts-with? stored "$argon2id$v=19$m=8192,t=1,p=1$"))
(expect "the hash verifies" (argon2id-verify "correct horse" stored) #t) (expect "the hash verifies" (argon2id-verify "correct horse" stored) #t)
(expect "another password does not" (argon2id-verify "correct horsf" stored) #f) (expect "another password does not" (argon2id-verify "correct horsf" stored) #f)
(expect-true "two hashes of a password differ, by the salt" (expect-true "two hashes of a password differ, by the salt"
(not (= stored (argon2id-hash "correct horse" #:iterations 1 #:memory-kib 8192)))) (not (= stored (argon2id-hash "correct horse" cheap))))
(expect "hashed from a plain function" (argon2id-verify "pw" (hash/sync "pw")) #t) (expect "hashed from a plain function" (argon2id-verify "pw" (hash/sync "pw")) #t)
(expect "a password outside ASCII" (argon2id-verify "blåbär" (hash/sync "blåbär")) #t) (expect "a password outside ASCII" (argon2id-verify "blåbär" (hash/sync "blåbär")) #t)
(expect "the default cost" (string-starts-with? (argon2id-hash "x") "$argon2id$v=19$m=65536,t=2,p=1$") #t) (expect "needs rehash: less than interactive" (argon2id-needs-rehash? stored argon2id-interactive) #t)
(expect "needs rehash: less than the defaults" (argon2id-needs-rehash? stored) #t) (expect "needs rehash: the same cost" (argon2id-needs-rehash? stored cheap) #f)
(expect "needs rehash: the same cost" (argon2id-needs-rehash? stored #:iterations 1 #:memory-kib 8192) #f) (expect "needs rehash: more memory asked" (argon2id-needs-rehash? stored (make-argon2id-cost 1 16384)) #t)
(expect "needs rehash: more memory asked" (argon2id-needs-rehash? stored #:iterations 1 #:memory-kib 16384) #t) (expect "needs rehash: more iterations asked" (argon2id-needs-rehash? stored (make-argon2id-cost 2 8192)) #t)
(expect "needs rehash: more iterations asked" (argon2id-needs-rehash? stored #:iterations 2 #:memory-kib 8192) #t) (expect "needs rehash: a cost higher than asked"
(expect "needs rehash: a cost higher than asked" (argon2id-needs-rehash? argon-stored-4 #:iterations 3 #:memory-kib 4096) #f) (argon2id-needs-rehash? argon-stored-4 (make-argon2id-cost 3 4096)) #f)
;; ---- Argon2id: errors in the program or in the stored data ---------------- ;; ---- Argon2id: errors in the program or in the stored data ----------------
(expect "a stored string that is not a hash" (raises? #(verify/sync "x" "hunter2")) #t) (expect "a stored string that is not a hash" (raises? #(verify/sync "x" "hunter2")) #t)
@ -255,30 +314,25 @@
(expect "the fields in another order" (raises? #(verify/sync "x" "$argon2id$v=19$t=3,m=4096,p=1$c2FsdHNhbHQ$aGFzaGhhc2g")) #t) (expect "the fields in another order" (raises? #(verify/sync "x" "$argon2id$v=19$t=3,m=4096,p=1$c2FsdHNhbHQ$aGFzaGhhc2g")) #t)
(expect "no hash" (raises? #(verify/sync "x" "$argon2id$v=19$m=4096,t=3,p=1$c2FsdHNhbHQ$")) #t) (expect "no hash" (raises? #(verify/sync "x" "$argon2id$v=19$m=4096,t=3,p=1$c2FsdHNhbHQ$")) #t)
(expect "PBKDF2" (raises? #(verify/sync "x" "$pbkdf2-sha256$i=1$c2FsdA$Eg+2z/z4syxD5yJSVsT4N6hlSMkszDVICAWYfLcL4Xs")) #t) (expect "PBKDF2" (raises? #(verify/sync "x" "$pbkdf2-sha256$i=1$c2FsdA$Eg+2z/z4syxD5yJSVsT4N6hlSMkszDVICAWYfLcL4Xs")) #t)
(expect "needs rehash of a stored string that is not a hash" (raises? #(argon2id-needs-rehash? "hunter2")) #t) (expect "needs rehash of a stored string that is not a hash" (raises? #(argon2id-needs-rehash? "hunter2" cheap)) #t)
(expect "a raise reaches a bjoroutine too" (expect "a raise reaches a bjoroutine too"
(match (try (argon2id-verify "x" "nonsense") #:catch (System.ArgumentException)) (match (try (argon2id-verify "x" "nonsense") #:catch (System.ArgumentException))
((Ok _) "returned") ((Ok _) "returned")
((Err _) "raised")) ((Err _) "raised"))
"raised") "raised")
(def salt (string->bytes ">A 16-bytes salt"))
(expect "no iterations" (raises? #(derive/sync "pw" salt 0 4096)) #t)
(expect "too little memory" (raises? #(derive/sync "pw" salt 1 7)) #t)
(expect "too much memory" (raises? #(derive/sync "pw" salt 1 2097152)) #t)
(expect "a short salt" (raises? #(derive/sync "pw" (make-array 15) 1 4096)) #t) (expect "a short salt" (raises? #(derive/sync "pw" (make-array 15) 1 4096)) #t)
(expect "a long salt" (raises? #(derive/sync "pw" (make-array 17) 1 4096)) #t) (expect "a long salt" (raises? #(derive/sync "pw" (make-array 17) 1 4096)) #t)
(expect "a short key" (raises? #(argon2id-derive-key "pw" salt #:iterations 1 #:memory-kib 8 #:length 15)) #t)
(expect "a hash with no iterations" (raises? #(argon2id-hash "pw" #:iterations 0 #:memory-kib 8192)) #t)
(expect "the smallest cost works"
(array-length (argon2id-derive-key "pw" salt #:iterations 1 #:memory-kib 8 #:length 16)) 16)
(expect "a new salt has the salt length" (array-length (make-argon2id-salt)) argon2id-salt-length) (expect "a new salt has the salt length" (array-length (make-argon2id-salt)) argon2id-salt-length)
(expect-true "two salts differ" (expect-true "two salts differ"
(not (= (bytes->hex (make-argon2id-salt)) (bytes->hex (make-argon2id-salt))))) (not (= (bytes->hex (make-argon2id-salt)) (bytes->hex (make-argon2id-salt)))))
(expect "a new salt derives a key" (expect "a new salt derives a key"
(array-length (argon2id-derive-key "pw" (make-argon2id-salt) #:iterations 1 #:memory-kib 8)) 32) (array-length (aead-key->bytes (argon2id-derive-key "pw" (make-argon2id-salt) (make-argon2id-cost 1 8)))) 32)
;; ---- Memory --------------------------------------------------------------- ;; ---- Random bytes and memory ----------------------------------------------
(def secret (make-aead-key Aegis256)) (expect "random-bytes" (array-length (random-bytes 7)) 7)
(expect "no random bytes" (array-length (random-bytes 0)) 0)
(expect "a negative count raises" (raises? #(random-bytes -1)) #t)
(def secret (random-bytes 32))
(wipe! secret) (wipe! secret)
(expect "wipe! clears every byte" (bytes->hex secret) (bytes->hex (make-array 32))) (expect "wipe! clears every byte" (bytes->hex secret) (bytes->hex (make-array 32)))
0) 0)