bjosodium/examples/vault.bjo
Linus Björnstam 2b42abb6d9 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>
2026-11-22 08:13:50 +01:00

26 lines
1 KiB
Text

;; 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/examples/vault.bjo — the example of the Readme.
;;
;; bjo run examples/vault.bjo
(import (std prelude))
(import (bjosodium core))
(defun (main)
;; A key from a password. Store the salt and the cost beside the data.
(def salt (make-argon2id-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. Data
;; that other devices open must say which cipher it was sealed with.
(def cipher XChaCha20Poly1305)
(def header (string->bytes "bookmarks v1"))
(def sealed (aead-seal cipher key (string->bytes "https://example.org") #:aad header))
(match (aead-unseal cipher key sealed #:aad header)
((Some plaintext) (println (bytes->string plaintext)) 0)
(None (println "wrong key, or the data was changed") 1)))