commit 911f4bcc4676ca6393f8eb43286fdddd69cf6b5665aca0770ceaf869fb73767b Author: Linus Björnstam Date: Sat Nov 21 21:07:27 2026 +0100 bjosodium: libsodium's authenticated encryption and Argon2id for Bjolang Co-Authored-By: Claude Opus 5.5 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ac014f9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +.bjo/ +*.dll +*.exe +*.pdb +*.bjobuild +*.runtimeconfig.json +*.deps.json diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d22367a --- /dev/null +++ b/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + 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 https://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/Readme.org b/Readme.org new file mode 100644 index 0000000..34b911d --- /dev/null +++ b/Readme.org @@ -0,0 +1,186 @@ +* bjosodium — libsodium for Bjolang + +Authenticated encryption with AEGIS-256 or XChaCha20-Poly1305, and password +hashing with Argon2id. The work is done by [[https://libsodium.org][libsodium]], through the .NET +binding [[https://libsodium.net][LibSodium.Net]]. + +#+BEGIN_SRC scheme +(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 key (argon2id-derive-key "correct horse" salt)) + + ;; Encrypt. The header is not secret, but a change to it is found. + (def cipher (preferred-cipher)) + (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))) +#+END_SRC + +** Using it + +#+BEGIN_SRC scheme +(depends + (package (name (bjosodium)) + (version (version-at-least "0.1.0")) + (source (path (dir "../bjosodium"))))) +#+END_SRC + +A program using this package declares no NuGet packages of its own. The +package declares LibSodium.Net and libsodium, and ~bjo~ restores them for +any build that uses the package. The libsodium package has the native +library for each platform: Windows, Linux (glibc and musl), macOS, Android, +iOS, tvOS and Mac Catalyst. Nothing has to be installed. + +** Operations + +| ~(aead-encrypt c key nonce data #:aad ad)~ | the ciphertext and the tag; the caller stores the nonce | +| ~(aead-decrypt c key nonce ct #:aad ad)~ | ~(Some data)~, or ~None~ when the tag does not verify | +| ~(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~ | +| ~(make-aead-key c)~ ~(make-aead-nonce c)~ | random bytes from the system's random source | +| ~(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 | +| ~(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-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-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 | +| ~(wipe! bytes)~ | sets every byte to 0, with ~sodium_memzero~ | + +| Cipher | Key | Nonce | Tag | +|---------------------+-----+-------+-----| +| ~Aegis256~ | 32 | 32 | 32 | +| ~XChaCha20Poly1305~ | 32 | 24 | 16 | + +The lengths are in bytes. ~#:aad~ is the associated data. It is not +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 +decrypted, such as a version, a revision or a device id. + +*Nonces.* Both ciphers have nonces large enough to be random, so a random +nonce for each message is safe and there is no counter to keep. Never encrypt +two messages with the same key and nonce. + +*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 +of the wrong length raises ~ArgumentException~, and so does an Argon2id cost +out of range. ~argon2id-verify~ and ~argon2id-needs-rehash?~ raise +~ArgumentException~ for a stored string that is not an Argon2id PHC string: +that is an error in the stored data, not a wrong password. + +*Threads and fibers.* 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. Encryption is fast and runs on the caller's thread. + +** Which cipher + +Both ciphers are safe. The choice is about speed, and the speed depends on +the CPU. + +- *AEGIS-256 is fast where the CPU has AES instructions*: the ARMv8 AES + instructions on 64-bit ARM, or AES-NI and AVX on x86. libsodium examines + the CPU when it starts and uses those instructions when they are there. +- *Without them*, libsodium runs AES in software, and then AEGIS-256 is + slower than XChaCha20-Poly1305. XChaCha20-Poly1305 needs no special + instructions. +- ~(aegis256-accelerated?)~ makes the same test as libsodium, from what .NET + reports about the CPU, and ~(preferred-cipher)~ chooses from it. + +*On Android phones AEGIS-256 is kept*, because a moderately modern phone has +the AES instructions: + +- The 64-bit Android library in the libsodium package has libsodium's + ARM code for AEGIS. The disassembly of + ~runtimes/android-arm64/native/libsodium.so~ in libsodium 1.0.20.2 has 301 + ~aese~ instructions. +- SUPERCOP measured libsodium's AEGIS-256 on a Raspberry Pi 5. Its CPU is a + Cortex-A76, which is also the large core of many phones from 2019 to 2021. + AEGIS-256 took about 4,440 cycles in the test where the fastest AES-256-GCM + took about 7,860. +- The ARMv8 AES instructions are optional. Most 64-bit phone CPUs have them. + Some low-cost CPUs do not, and Android encrypts the storage of those phones + with Adiantum, not AES. On such a phone, ~preferred-cipher~ returns + ~XChaCha20Poly1305~. +- The 32-bit ARM libraries (~android-arm~, ~linux-arm~) have no ~aese~ + instructions, so a 32-bit process always runs AEGIS in software. + ~aegis256-accelerated?~ is false there, because .NET has the ARM AES + instructions only on 64-bit ARM. + +Not measured on a phone: this package was run only on Linux x64. + +*Write the cipher into the data.* A file encrypted on one device must open on +the others. Put the cipher in the header, and include the header in +~#:aad~. Each device can then decrypt both, whichever it prefers to write. + +On an AMD Ryzen 9 5900X, from ~bench/ciphers.bjo~. A call makes a new array +for its result, and the times include it. At 1 MiB that array is most of the +difference between this table and libsodium's own speed. + +| Operation | 1 KiB | 1 MiB | +|----------------------------+--------+--------| +| encrypt AEGIS-256 | 139 ns | 244 µs | +| encrypt XChaCha20-Poly1305 | 774 ns | 666 µs | +| decrypt AEGIS-256 | 148 ns | 262 µs | +| decrypt XChaCha20-Poly1305 | 786 ns | 729 µs | + +** 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~). ~argon2id-verify~ +also accepts a string made elsewhere with more lanes. + +| Cost | Name in libsodium | Here on a Ryzen 9 5900X | +|--------------------------------+-------------------+-------------------------| +| ~t=2~, ~m=65536~ (64 MiB), the default | INTERACTIVE | 50 ms | +| ~t=3~, ~m=262144~ (256 MiB) | MODERATE | 293 ms | + +- 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 + highest cost that the slowest device accepts, and measure it on that + device. +- The memory must be available. 256 MiB can be too much for a phone that + is short of memory. +- 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. +- ~argon2id-derive-key~ takes a salt of exactly 16 bytes, and gives 32 bytes + unless ~#:length~ says otherwise (at least 16). +- The memory is from 8 KiB to 2097151 KiB (just under 2 GiB). + +** Versions + +LibSodium.Net 0.16.0-alpha is a pre-release. When it starts, it raises +~LibSodiumException~ if the native library is not the libsodium 1.0.x that it +was built for, which is 1.0.20. So the manifest fixes both: + +- LibSodium.Net exactly 0.16.0-alpha; +- libsodium from 1.0.20.2, which is the first build of 1.0.20 with the Android + libraries, up to but not including 1.0.21. + +libsodium 1.0.21 makes Argon2 faster on ARM with NEON. To get it, change both +versions together, when a version of LibSodium.Net for 1.0.21 or later is +released. + +** Not here + +LibSodium.Net has more of libsodium than this package exposes: secret streams, +HKDF, public-key encryption, signatures. Add them when they are needed. +Data goes in and out as arrays, not as spans. + +** Try it + +#+BEGIN_SRC sh +bjo run tests/core.bjo # every line should start with "ok:" +bjo run examples/vault.bjo # the example above +bjo bench bench/ciphers.bjo --all +#+END_SRC + +The tests use libsodium's own test vectors for AEGIS-256, +XChaCha20-Poly1305 and Argon2id. diff --git a/bench/ciphers.bjo b/bench/ciphers.bjo new file mode 100644 index 0000000..0eeab1b --- /dev/null +++ b/bench/ciphers.bjo @@ -0,0 +1,59 @@ +;; 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/bench/ciphers.bjo — the two ciphers side by side, and the cost +;; of Argon2id. +;; +;; bjo bench bench/ciphers.bjo --all +;; bjo bench bench/ciphers.bjo --compare-within aead +;; +;; The times include this module's work for each call: the checks of the +;; lengths and a new array for the result. + +(import (std prelude)) +(import (std bench)) +(import (bjosodium core)) + +(def/bench "encrypt AEGIS-256" + #:group "aead" + #:params ((bytes [1024 1048576])) + #:setup ((key (make-aead-key Aegis256)) + (nonce (make-aead-nonce Aegis256)) + (message (: (make-array bytes) (Array byte)))) + (aead-encrypt Aegis256 key nonce message)) + +(def/bench "encrypt XChaCha20-Poly1305" + #:group "aead" + #:params ((bytes [1024 1048576])) + #:setup ((key (make-aead-key XChaCha20Poly1305)) + (nonce (make-aead-nonce XChaCha20Poly1305)) + (message (: (make-array bytes) (Array byte)))) + (aead-encrypt XChaCha20Poly1305 key nonce message)) + +(def/bench "decrypt AEGIS-256" + #:group "aead" + #:params ((bytes [1024 1048576])) + #:setup ((key (make-aead-key Aegis256)) + (nonce (make-aead-nonce Aegis256)) + (boxed (aead-encrypt Aegis256 key nonce (: (make-array bytes) (Array byte))))) + (aead-decrypt Aegis256 key nonce boxed)) + +(def/bench "decrypt XChaCha20-Poly1305" + #:group "aead" + #:params ((bytes [1024 1048576])) + #:setup ((key (make-aead-key XChaCha20Poly1305)) + (nonce (make-aead-nonce XChaCha20Poly1305)) + (boxed (aead-encrypt XChaCha20Poly1305 key nonce (: (make-array bytes) (Array byte))))) + (aead-decrypt XChaCha20Poly1305 key nonce boxed)) + +;; The default cost, and libsodium's MODERATE cost. +(def/bench "argon2id-derive-key" + #:group "argon2id" + #:params ((cost ["t=2 m=64MiB" "t=3 m=256MiB"])) + #:setup ((salt (: (make-array argon2id-salt-length) (Array byte))) + (t (if (= cost "t=2 m=64MiB") 2 3)) + (m (if (= cost "t=2 m=64MiB") 65536 262144))) + (argon2id-derive-key "correct horse battery staple" salt #:iterations t #:memory-kib m)) + +(run-benches) diff --git a/examples/vault.bjo b/examples/vault.bjo new file mode 100644 index 0000000..806bfa3 --- /dev/null +++ b/examples/vault.bjo @@ -0,0 +1,24 @@ +;; 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 key (argon2id-derive-key "correct horse" salt)) + + ;; Encrypt. The header is not secret, but a change to it is found. + (def cipher (preferred-cipher)) + (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))) diff --git a/manifest.bjodat b/manifest.bjodat new file mode 100644 index 0000000..d65b751 --- /dev/null +++ b/manifest.bjodat @@ -0,0 +1,20 @@ +(package + (name (bjosodium)) + (version "0.1.0") + (description "libsodium for Bjolang: AEGIS-256 and XChaCha20-Poly1305 encryption, and Argon2id password hashing.") + (license "MPL-2.0") + + ;; LibSodium.Net is the .NET binding. The libsodium package has the native + ;; library, built for each platform, Android and iOS too, so nothing has to + ;; be installed. + ;; + ;; Both versions are fixed. LibSodium.Net raises when it starts if the + ;; native library is not the libsodium 1.0.x it was built for (1.0.20 for + ;; 0.16.0-alpha). 1.0.20.2 is the first build of 1.0.20 with Android + ;; libraries in it. + (packages + (nuget (id "LibSodium.Net") (version "[0.16.0-alpha]")) + (nuget (id "libsodium") (version "[1.0.20.2, 1.0.21)"))) + + ;; A library: there is no src/main.bjo. + ) diff --git a/packages.lock.json b/packages.lock.json new file mode 100644 index 0000000..36a504b --- /dev/null +++ b/packages.lock.json @@ -0,0 +1,22 @@ +{ + "version": 1, + "dependencies": { + "net11.0": { + "libsodium": { + "type": "Direct", + "requested": "[1.0.20.2, 1.0.21)", + "resolved": "1.0.20.2", + "contentHash": "FButtPK6HZvOewaE20F1HXNJn4qOoGAf7FEDm0VbWJ+xBX9pN9+2nkQQnfaLz+Ae5KuEzRoe1GHO00UpabgNxA==" + }, + "LibSodium.Net": { + "type": "Direct", + "requested": "[0.16.0-alpha, 0.16.0-alpha]", + "resolved": "0.16.0-alpha", + "contentHash": "uNW5uuT2QEu5zUSDAbNyXM/RPZjnLjMEp88uYMCkH2yr9+jX7LpZsV9JZimdIABKiHivfGqSJAXmj3Bd2tmJUQ==", + "dependencies": { + "libsodium": "1.0.20.1" + } + } + } + } +} \ No newline at end of file diff --git a/src/core.bjo b/src/core.bjo new file mode 100644 index 0000000..a345211 --- /dev/null +++ b/src/core.bjo @@ -0,0 +1,434 @@ +;; 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/core.bjo — the module (bjosodium core): authenticated +;; encryption with AEGIS-256 or XChaCha20-Poly1305, and password hashing with +;; Argon2id. The work is done by libsodium, through LibSodium.Net. +;; +;; - Keys, nonces, data and associated data are (Array byte). A password is a +;; string, used as its UTF-8 bytes. +;; - Encryption is AEAD: the result has a tag, and 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. +;; - `aead-encrypt` takes a nonce from the caller. `aead-seal` makes a random +;; nonce and puts it in front of the result. +;; - Both ciphers have nonces large enough to be random: do not count them. +;; 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, +;; 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-key-length cipher-nonce-length cipher-tag-length + aegis256-accelerated? preferred-cipher + ;; Keys and nonces + make-aead-key make-aead-nonce + ;; Encryption + aead-encrypt aead-decrypt aead-seal aead-unseal + ;; Argon2id + argon2id-derive-key argon2id-hash argon2id-verify argon2id-needs-rehash? + make-argon2id-salt argon2id-salt-length default-argon2id-iterations default-argon2id-memory-kib + ;; Memory + 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=,t=,p=$$`. 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=,t=,p=$$.") + (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$$`, +;; 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)) diff --git a/tests/core.bjo b/tests/core.bjo new file mode 100644 index 0000000..b2323ed --- /dev/null +++ b/tests/core.bjo @@ -0,0 +1,284 @@ +;; 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/tests/core.bjo — (bjosodium core) against libsodium's own test +;; vectors, and the failures that must give `None` or raise. +;; +;; bjo run tests/core.bjo +;; +;; Every line should start with "ok:". +;; +;; The vectors are from libsodium's test suite (test/default/ in the +;; libsodium repository): +;; - AEGIS-256: the fourth entry of `tests[]` in aead_aegis256.c. +;; - XChaCha20-Poly1305: `tv()` in aead_xchacha20poly1305.c, with the +;; output in aead_xchacha20poly1305.exp. +;; - Argon2id: `tv3()` in pwhash_argon2id.c, with the results in +;; pwhash_argon2id.exp. Entries 2, 4 and 5 verify, entry 0 does not. +;; +;; `main` is a bjoroutine, so the Argon2id functions are tried in both +;; colours: from `main`, and from the plain `defun`s below. + +(import (std prelude)) +(import (std simpletest)) +(import (std crypto hash)) +(import (bjosodium core)) + +(import/class + (ArgumentException (: System.ArgumentException (-> string ArgumentException)))) + +(: (-> string (Array byte))) +(defun (unhex text) + (match (hex->bytes text) + ((Some bytes) bytes) + (None (raise (cast Exception (ArgumentException. (str "Not hex: " text))))))) + +(: (-> (Option (Array byte)) string)) +(defun (opened result) + (match result + ((Some bytes) (bytes->hex bytes)) + (None "None"))) + +(: (-> (-> %a) bool)) +(defun (raises? thunk) + (match (try (thunk) #:catch (System.ArgumentException)) + ((Ok _) #f) + ((Err _) #t))) + +;; A copy of `bytes` with bit 0 of byte `i` changed. +(: (-> (Array byte) int (Array byte))) +(defun (flipped bytes i) + (def copy (ro-span->array (array->ro-span bytes))) + (array-set! copy i (cast byte (bitwise-xor (cast int (array-ref copy i)) 1))) + copy) + +(: (-> (Array byte) int (Array byte))) +(defun (first-bytes bytes n) (ro-span->array (array->ro-span bytes #:to n))) + +;; The non-bjoroutine versions, called from `main` through these. +(: (-> string (Array byte) int int (Array byte))) +(defun (derive/sync password salt t m) + (argon2id-derive-key password salt #:iterations t #:memory-kib m)) + +(: (-> string string bool)) +(defun (verify/sync password stored) (argon2id-verify password stored)) + +(: (-> string string)) +(defun (hash/sync password) (argon2id-hash password #:iterations 1 #:memory-kib 8192)) + +;; ---- Vectors ---------------------------------------------------------------- + +(def aegis-key (unhex "b8c6e8cea59ca9fd2922530ee61911c1ed1c5af98be8fb03cbb449adcea0ed83")) +(def aegis-nonce (unhex "af5bc1abe7bafadee790390277874cdfcc1ac1955f249d1131555d345832f555")) +(def aegis-message (unhex "b6c15f560be043d06aa27e15d8c901af6b19db7a15e1")) +(def aegis-ad (unhex "d899366a0b4e4d86cce5ba61aca2a84349c8de5757e008e94e7d7a3703")) +(def aegis-ciphertext "4c8496dfa6c419ef3c4867769a9014bd17118c22eef5") +(def aegis-tag "f81ceacaaae6263c33f836fa26d92b0f08eb0796135c7fe312c93add6a208e8a") + +(def xchacha-key (unhex "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f")) +(def xchacha-nonce (unhex "07000000404142434445464748494a4b4c4d4e4f50515253")) +(def xchacha-ad (unhex "50515253c0c1c2c3c4c5c6c7")) +(def xchacha-message + (string->bytes "Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it.")) +(def xchacha-ciphertext + (str "f8ebea4875044066fc162a0604e171feecfb3d20425248563bcfd5a155dcc47b" + "bda70b86e5ab9b55002bd1274c02db35321acd7af8b2e2d25015e136b7679458" + "e9f43243bf719d639badb5feac03f80a19a96ef10cb1d15333a837b90946ba38" + "54ee74da3f2585efc7e1e170e17e15e563e7")) +(def xchacha-tag "7601f4f85cafa8e5877614e143e68420") + +;; tv3 entry 4: t=19, m=4096, salt ">A 16-bytes salt". +(def argon-password-4 "^T5H$JYt39n%K*j:W]!1s?vg!:jGi]Ax?..l7[p0v:1jHTpla9;]bUN;?bWyCbtqg ") +(def argon-stored-4 "$argon2id$v=19$m=4096,t=19,p=1$PkEgMTYtYnl0ZXMgc2FsdA$ltB/ue1kPtBMBGfsysMpPigE6hiNEKZ9vs8vLNVDQGA") +(def argon-hash-4 "96d07fb9ed643ed04c0467eccac3293e2804ea188d10a67dbecf2f2cd5434060") +;; tv3 entry 2: the empty password, t=2, m=4882. +(def argon-stored-2 "$argon2id$v=19$m=4882,t=2,p=1$bA81arsiXysd3WbTRzmEOw$Nm8QBM+7RH1DXo9rvp5cwKEOOOfD2g6JuxlXihoNcpE") +(def argon-salt-2 (unhex "6c0f356abb225f2b1ddd66d34739843b")) +(def argon-hash-2 "366f1004cfbb447d435e8f6bbe9e5cc0a10e38e7c3da0e89bb19578a1a0d7291") +;; tv3 entry 5: three lanes, which libsodium verifies but does not make. +(def argon-password-5 "K3S=KyH#)36_?]LxeR8QNKw6X=gFbxai$C%29V*") +(def argon-stored-5 "$argon2id$v=19$m=4096,t=1,p=3$PkEgcHJldHR5IGxvbmcgc2FsdA$HUqx5Z1b/ZypnUrvvJ5UC2Q+T6Q1WwASK/Kr9dRbGA0") +;; tv3 entry 0: t=0, which libsodium rejects. +(def argon-stored-0 "$argon2id$v=19$m=4096,t=0,p=1$X1NhbHQAAAAAAAAAAAAAAA$bWh++MKN1OiFHKgIWTLvIi1iHicmHH7+Fv3K88ifFfI") + +(: (-> Cipher void)) +(defun (check-cipher cipher) + (def name (written cipher)) + (def key (make-aead-key cipher)) + (def nonce (make-aead-nonce cipher)) + (def aad (string->bytes "header, revision 7")) + (def message (string->bytes "https://example.org/ — a bookmark")) + (def boxed (aead-encrypt cipher key nonce message #:aad aad)) + (def tag-length (cipher-tag-length cipher)) + (expect #"${name}: the ciphertext is a tag longer" (array-length boxed) + (+ (array-length message) tag-length)) + (expect #"${name}: round trip" (opened (aead-decrypt cipher key nonce boxed #:aad aad)) + (bytes->hex message)) + (expect #"${name}: a changed ciphertext byte" (opened (aead-decrypt cipher key nonce (flipped boxed 0) #:aad aad)) + "None") + (expect #"${name}: a changed tag byte" + (opened (aead-decrypt cipher key nonce (flipped boxed (- (array-length boxed) 1)) #:aad aad)) + "None") + (expect #"${name}: another key" (opened (aead-decrypt cipher (make-aead-key cipher) nonce boxed #:aad aad)) + "None") + (expect #"${name}: another nonce" (opened (aead-decrypt cipher key (flipped nonce 3) boxed #:aad aad)) + "None") + (expect #"${name}: other associated data" + (opened (aead-decrypt cipher key nonce boxed #:aad (string->bytes "header, revision 6"))) + "None") + (expect #"${name}: no associated data" (opened (aead-decrypt cipher key nonce boxed)) "None") + (expect #"${name}: cut short" (opened (aead-decrypt cipher key nonce (first-bytes boxed (- (array-length boxed) 1)) #:aad aad)) + "None") + (expect #"${name}: shorter than a tag" (opened (aead-decrypt cipher key nonce (first-bytes boxed (- tag-length 1)) #:aad aad)) + "None") + ;; The empty message: only the tag. + (def empty (aead-encrypt cipher key nonce (make-array 0))) + (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)) "") + ;; Sealed: a new nonce in front. + (def sealed (aead-seal cipher key message #:aad aad)) + (expect #"${name}: sealed is a nonce and a tag longer" (array-length sealed) + (+ (cipher-nonce-length cipher) (array-length message) tag-length)) + (expect #"${name}: unsealed" (opened (aead-unseal cipher key sealed #:aad aad)) (bytes->hex message)) + (expect-true #"${name}: each seal has its own nonce" + (not (= (bytes->hex (aead-seal cipher key message #:aad aad)) (bytes->hex sealed)))) + (expect #"${name}: a changed nonce in a sealed message" (opened (aead-unseal cipher key (flipped sealed 0) #:aad aad)) + "None") + (expect #"${name}: a sealed message with other associated data" (opened (aead-unseal cipher key sealed)) + "None") + (expect #"${name}: a sealed message shorter than a nonce and a tag" + (opened (aead-unseal cipher key (first-bytes sealed (- (+ (cipher-nonce-length cipher) tag-length) 1)))) + "None") + (def sealed-empty (aead-seal cipher key (make-array 0))) + (expect #"${name}: an empty message sealed" (opened (aead-unseal cipher key sealed-empty)) "") + ;; 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 short nonce raises" (raises? #(aead-encrypt cipher key (make-array 12) message)) #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) + ;; ---- Lengths -------------------------------------------------------------- + (expect "AEGIS-256 key" (cipher-key-length Aegis256) 32) + (expect "AEGIS-256 nonce" (cipher-nonce-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 tag" (cipher-tag-length XChaCha20Poly1305) 16) + (expect "a key has the key length" (array-length (make-aead-key XChaCha20Poly1305)) 32) + (expect "a nonce has the nonce length" (array-length (make-aead-nonce XChaCha20Poly1305)) 24) + (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) + (if (aegis256-accelerated?) Aegis256 XChaCha20Poly1305)) + (println #"note: aegis256-accelerated? is ${(written (aegis256-accelerated?))} here") + + ;; ---- Known answers -------------------------------------------------------- + (expect "AEGIS-256 vector" (bytes->hex (aead-encrypt Aegis256 aegis-key aegis-nonce aegis-message #:aad aegis-ad)) + (str aegis-ciphertext aegis-tag)) + (expect "AEGIS-256 vector decrypts" + (opened (aead-decrypt Aegis256 aegis-key aegis-nonce (unhex (str aegis-ciphertext aegis-tag)) #:aad aegis-ad)) + (bytes->hex aegis-message)) + (expect "XChaCha20-Poly1305 vector" + (bytes->hex (aead-encrypt XChaCha20Poly1305 xchacha-key xchacha-nonce xchacha-message #:aad xchacha-ad)) + (str xchacha-ciphertext xchacha-tag)) + (expect "XChaCha20-Poly1305 vector decrypts" + (opened (aead-decrypt XChaCha20Poly1305 xchacha-key xchacha-nonce + (unhex (str xchacha-ciphertext xchacha-tag)) #:aad xchacha-ad)) + (bytes->hex xchacha-message)) + (expect "a ciphertext of one cipher does not open with the other" + (opened (aead-decrypt XChaCha20Poly1305 aegis-key (first-bytes aegis-nonce 24) + (unhex (str aegis-ciphertext aegis-tag)) #:aad aegis-ad)) + "None") + + ;; ---- Behaviour, for each cipher ------------------------------------------- + (check-cipher Aegis256) + (check-cipher XChaCha20Poly1305) + + ;; ---- Argon2id: known answers ---------------------------------------------- + (expect "derive: tv3 entry 4" + (bytes->hex (argon2id-derive-key argon-password-4 (string->bytes ">A 16-bytes salt") + #:iterations 19 #:memory-kib 4096)) + argon-hash-4) + (expect "derive: tv3 entry 4, from a plain function" + (bytes->hex (derive/sync argon-password-4 (string->bytes ">A 16-bytes salt") 19 4096)) + argon-hash-4) + (expect "derive: tv3 entry 2, the empty password" + (bytes->hex (argon2id-derive-key "" argon-salt-2 #:iterations 2 #:memory-kib 4882)) + argon-hash-2) + (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 2" (argon2id-verify "" argon-stored-2) #t) + (expect "verify: tv3 entry 5, three lanes" (argon2id-verify argon-password-5 argon-stored-5) #t) + (expect "verify: tv3 entry 0, no iterations" (argon2id-verify "" argon-stored-0) #f) + (expect "verify: a wrong password" (argon2id-verify "^T5H" argon-stored-4) #f) + ;; The first letter of the hash, as the last one holds bits that base64 pads. + (expect "verify: one changed letter of the hash" + (argon2id-verify argon-password-4 + "$argon2id$v=19$m=4096,t=19,p=1$PkEgMTYtYnl0ZXMgc2FsdA$mtB/ue1kPtBMBGfsysMpPigE6hiNEKZ9vs8vLNVDQGA") + #f) + (expect "verify: one changed letter of the salt" + (argon2id-verify argon-password-4 + "$argon2id$v=19$m=4096,t=19,p=1$QkEgMTYtYnl0ZXMgc2FsdA$ltB/ue1kPtBMBGfsysMpPigE6hiNEKZ9vs8vLNVDQGA") + #f) + (expect "verify: another cost in the string" + (argon2id-verify argon-password-4 + "$argon2id$v=19$m=4096,t=18,p=1$PkEgMTYtYnl0ZXMgc2FsdA$ltB/ue1kPtBMBGfsysMpPigE6hiNEKZ9vs8vLNVDQGA") + #f) + + ;; ---- Argon2id: hash and verify -------------------------------------------- + (def stored (argon2id-hash "correct horse" #:iterations 1 #:memory-kib 8192)) + (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 "another password does not" (argon2id-verify "correct horsf" stored) #f) + (expect-true "two hashes of a password differ, by the salt" + (not (= stored (argon2id-hash "correct horse" #:iterations 1 #:memory-kib 8192)))) + (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 "the default cost" (string-starts-with? (argon2id-hash "x") "$argon2id$v=19$m=65536,t=2,p=1$") #t) + (expect "needs rehash: less than the defaults" (argon2id-needs-rehash? stored) #t) + (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 #:iterations 1 #:memory-kib 16384) #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" (argon2id-needs-rehash? argon-stored-4 #:iterations 3 #:memory-kib 4096) #f) + + ;; ---- 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 "the empty stored string" (raises? #(verify/sync "x" "")) #t) + (expect "Argon2i, not Argon2id" + (raises? #(verify/sync "x" "$argon2i$v=19$m=4096,t=3,p=1$c2FsdHNhbHQ$aGFzaGhhc2g")) #t) + (expect "another version" (raises? #(verify/sync "x" "$argon2id$v=16$m=4096,t=3,p=1$c2FsdHNhbHQ$aGFzaGhhc2g")) #t) + (expect "a cost that is not a number" (raises? #(verify/sync "x" "$argon2id$v=19$m=x,t=3,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 "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 "a raise reaches a bjoroutine too" + (match (try (argon2id-verify "x" "nonsense") #:catch (System.ArgumentException)) + ((Ok _) "returned") + ((Err _) "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 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-true "two salts differ" + (not (= (bytes->hex (make-argon2id-salt)) (bytes->hex (make-argon2id-salt))))) + (expect "a new salt derives a key" + (array-length (argon2id-derive-key "pw" (make-argon2id-salt) #:iterations 1 #:memory-kib 8)) 32) + + ;; ---- Memory --------------------------------------------------------------- + (def secret (make-aead-key Aegis256)) + (wipe! secret) + (expect "wipe! clears every byte" (bytes->hex secret) (bytes->hex (make-array 32))) + 0)