feat(keys): halkyon_keys, an account's keys on the device
ADR 0017's step 1, on libsodium (sodium 4.1.0+1, whose build hook compiles the libsodium 1.0.22 it ships: a C compiler and make wherever it builds): - Argon2id (64 MiB, 3 passes, kept with the account and never below that) makes a master key, which libsodium's KDF splits into SRP's secret (x) and the key-encryption key. - The account's X25519 and Ed25519 key pairs, their private halves wrapped with XChaCha20-Poly1305 under the KEK and under the recovery key, bound to their public keys. - A 24-word BIP-39 recovery phrase (the English list, MIT) and the recovery key derived from it. - Data keys sealed to the account with crypto_box_seal, bound to their IDs; content in ADR 0002's envelope, encrypted with a data key and signed with Ed25519 (detached), bound to a context the caller names. - Secrets in libsodium's guarded memory where its API takes them. - Tests: libsodium's Argon2id known answers, BIP-39's English vectors, round trips and every refusal. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Tizian 「ティツィアーン」 <raisondetredev@pm.me>
This commit is contained in:
parent
470a0b633c
commit
3bc0bae6e3
20 changed files with 4495 additions and 0 deletions
31
packages/halkyon_keys/.gitignore
vendored
Normal file
31
packages/halkyon_keys/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
# Miscellaneous
|
||||
*.class
|
||||
*.log
|
||||
*.pyc
|
||||
*.swp
|
||||
.DS_Store
|
||||
.atom/
|
||||
.buildlog/
|
||||
.history
|
||||
.svn/
|
||||
migrate_working_dir/
|
||||
|
||||
# IntelliJ related
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
.idea/
|
||||
|
||||
# The .vscode folder contains launch configuration and tasks you configure in
|
||||
# VS Code which you may wish to be included in version control, so this line
|
||||
# is commented out by default.
|
||||
#.vscode/
|
||||
|
||||
# Flutter/Dart/Pub related
|
||||
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
|
||||
/pubspec.lock
|
||||
**/doc/api/
|
||||
.dart_tool/
|
||||
.flutter-plugins-dependencies
|
||||
/build/
|
||||
/coverage/
|
||||
26
packages/halkyon_keys/BIP39-LICENSE
Normal file
26
packages/halkyon_keys/BIP39-LICENSE
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
The English word list in lib/src/bip39_english.dart is BIP-39's
|
||||
(https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt), by Marek
|
||||
Palatinus, Pavol Rusnak, Aaron Voisine and Sean Bowe, 2013. BIP-39 falls under
|
||||
the MIT License:
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2013 Marek Palatinus, Pavol Rusnak, Aaron Voisine, Sean Bowe
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
661
packages/halkyon_keys/LICENSE
Normal file
661
packages/halkyon_keys/LICENSE
Normal file
|
|
@ -0,0 +1,661 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
49
packages/halkyon_keys/README.md
Normal file
49
packages/halkyon_keys/README.md
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
# halkyon_keys
|
||||
|
||||
An account's keys on the device (ADR 0017), in pure Dart on libsodium (the `sodium`
|
||||
package, its sumo API). Every primitive is libsodium's; this package only puts them
|
||||
together. Callers pass a `SodiumSumo` from `await SodiumSumoInit.init()`.
|
||||
|
||||
`sodium`'s build hook compiles the libsodium it ships (1.0.22), so every machine that
|
||||
builds or tests a package depending on this one needs a C compiler and `make`.
|
||||
|
||||
## What it provides
|
||||
|
||||
| Piece | API | Parameters |
|
||||
|---|---|---|
|
||||
| The password's keys | `newPasswordSalt`, `derivePasswordKeys` → `PasswordKeys` (`srpSecret`, `srpPrivateValue`, `keyEncryptionKey`) | Argon2id v1.3, 64 MiB, 3 passes (`PasswordKdf.current`), a 16-byte salt, a 32-byte master key; libsodium's KDF (context `hlkpass1`) splits it into SRP's secret (subkey 1, whose 256 bits big-endian are SRP's x) and the key-encryption key (subkey 2) |
|
||||
| The costs kept with an account | `PasswordKdf` (`toJson`, `fromJson`) | kept beside the salt, so they can be raised for new passwords; `fromJson` refuses another algorithm or costs below `PasswordKdf.minimum`, kept apart from the current costs so raising those never locks out an older account |
|
||||
| The account's key pairs | `AccountKeys.generate` | X25519 to encrypt to, Ed25519 to sign with |
|
||||
| Their wrapping | `wrapAccountKeys`, `unwrapAccountKeys` → `WrappedAccountKeys` (`nonce`, `cipherText`) | XChaCha20-Poly1305, a random 24-byte nonce, the private halves (32 + 64 bytes) as plaintext, both public keys and a version label as additional data; unwrapping also rebuilds both public keys from the private halves and compares them with those given |
|
||||
| The recovery phrase | `newRecoveryPhrase`, `recoveryPhraseOf`, `entropyOfRecoveryPhrase` | BIP-39, English list: 24 words for 256 random bits and an 8-bit checksum; case and spacing as typed don't count |
|
||||
| The recovery key | `recoveryKeyOf` | libsodium's KDF over the phrase's 256 bits (context `hlkrcvy1`, subkey 1); a 12- to 21-word BIP-39 phrase is refused |
|
||||
| Data keys | `DataKey.generate`, `sealDataKey`, `openDataKey` | a random XChaCha20-Poly1305 key per store with an ID (1 to 255 bytes of UTF-8), sealed with its ID to the account's X25519 key (`crypto_box_seal`); it opens only under the ID it was sealed with |
|
||||
| Content | `sealContent`, `openContent` → `SealedContent` (`keyId`, `nonce`, `payload`, `signature`) | ADR 0002's envelope: XChaCha20-Poly1305 under the data key, the key's ID and a caller's `context` (its table and row) as additional data; the author's Ed25519 signature, detached, over the ID, nonce, payload and context, each framed by its length; the signature is checked before anything is decrypted |
|
||||
| Refusals | `KeyRefused` with a `KeyRefusal` | `wrongKeyOrTampered`, `notTheAccountsKeys`, `wrongDataKey`, `forgedSignature`, `weakPasswordKdf`, `phraseLength`, `phraseWord`, `phraseChecksum` |
|
||||
|
||||
Secrets stay in libsodium's guarded memory (`SecureKey`) where its API takes one:
|
||||
the master key, both password subkeys, the private halves of the key pairs, the
|
||||
recovery key and data keys. Wrapping, sealing a data key and reading x copy key bytes
|
||||
to the Dart heap for a moment, wiped afterwards. `dispose` wipes and frees a holder's
|
||||
keys, which may not be read afterwards.
|
||||
|
||||
## What never leaves the device
|
||||
|
||||
The password, the master key, SRP's secret and x, the key-encryption key, the recovery
|
||||
phrase and its key, the private halves of the key pairs, data keys and content in the
|
||||
clear. What the register keeps is the salt and the costs, both public keys, the private
|
||||
keys wrapped twice (under the key-encryption key and under the recovery key), data keys
|
||||
sealed to the account, and sealed content: none of it opens without the password or the
|
||||
phrase.
|
||||
|
||||
## Tests
|
||||
|
||||
`dart test`: libsodium's own Argon2id known answers (its `pwhash_argon2id` test, so the
|
||||
compiled libsodium is the one these keys were made with), BIP-39's English vectors
|
||||
(trezor/python-mnemonic's `vectors.json`, MIT), the word list's SHA-256, round trips,
|
||||
and every refusal.
|
||||
|
||||
## Licence
|
||||
|
||||
GNU Affero General Public License, version 3 or any later version (`LICENSE`). The
|
||||
English word list is BIP-39's, under the MIT License (`BIP39-LICENSE`).
|
||||
9
packages/halkyon_keys/analysis_options.yaml
Normal file
9
packages/halkyon_keys/analysis_options.yaml
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
# The workspace's lint rules (see ../../analysis_options.yaml).
|
||||
include: ../../analysis_options.yaml
|
||||
|
||||
analyzer:
|
||||
exclude:
|
||||
- build/**
|
||||
|
||||
formatter:
|
||||
trailing_commas: preserve
|
||||
23
packages/halkyon_keys/lib/halkyon_keys.dart
Normal file
23
packages/halkyon_keys/lib/halkyon_keys.dart
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
/// An account's keys on the device (ADR 0017): what the password unlocks
|
||||
/// (Argon2id, split into SRP's x and the key-encryption key), the account's
|
||||
/// key pairs and their wrapping, the recovery phrase and its key, data keys
|
||||
/// sealed to the account, and content sealed and signed in ADR 0002's
|
||||
/// envelope. libsodium (the `sodium` package, its sumo API for Argon2id)
|
||||
/// does every primitive; nothing here is ever sent but what is wrapped,
|
||||
/// sealed or public.
|
||||
library;
|
||||
|
||||
export 'src/account_keys.dart'
|
||||
show AccountKeys, WrappedAccountKeys, unwrapAccountKeys, wrapAccountKeys;
|
||||
export 'src/data_keys.dart' show DataKey, openDataKey, sealDataKey;
|
||||
export 'src/key_refused.dart';
|
||||
export 'src/password_keys.dart'
|
||||
show PasswordKdf, PasswordKeys, derivePasswordKeys, newPasswordSalt;
|
||||
export 'src/recovery_phrase.dart'
|
||||
show
|
||||
entropyOfRecoveryPhrase,
|
||||
newRecoveryPhrase,
|
||||
recoveryEntropyBytes,
|
||||
recoveryKeyOf,
|
||||
recoveryPhraseOf;
|
||||
export 'src/sealed_content.dart' show SealedContent, openContent, sealContent;
|
||||
173
packages/halkyon_keys/lib/src/account_keys.dart
Normal file
173
packages/halkyon_keys/lib/src/account_keys.dart
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:halkyon_keys/src/key_refused.dart';
|
||||
import 'package:sodium/sodium_sumo.dart';
|
||||
|
||||
/// An account's key pairs (ADR 0017): X25519 to encrypt to (data keys are
|
||||
/// sealed to it), Ed25519 to sign with (what the account writes carries its
|
||||
/// signature). Made on the device; their private halves leave it only
|
||||
/// wrapped ([wrapAccountKeys]), under the password's key-encryption key and
|
||||
/// again under the recovery key, so the register keeps them and can never
|
||||
/// use them.
|
||||
|
||||
/// What the wrapping binds itself to besides the public keys: a version, so
|
||||
/// a later format can't be mistaken for this one.
|
||||
final _wrappingLabel = utf8.encode('halkyon account keys v1');
|
||||
|
||||
/// The account's two key pairs, their private halves in libsodium's guarded
|
||||
/// memory until [dispose].
|
||||
final class AccountKeys._(
|
||||
/// X25519, to encrypt to.
|
||||
final KeyPair encryption,
|
||||
|
||||
/// Ed25519, to sign with.
|
||||
final KeyPair signing,
|
||||
) {
|
||||
/// New key pairs, made at sign-up (or, for someone anonymous, when the
|
||||
/// device first needs them).
|
||||
factory generate(SodiumSumo sodium) =>
|
||||
AccountKeys._(sodium.crypto.box.keyPair(), sodium.crypto.sign.keyPair());
|
||||
|
||||
/// The public key data keys are sealed to; the register keeps and hands it
|
||||
/// out.
|
||||
Uint8List get encryptionPublicKey => encryption.publicKey;
|
||||
|
||||
/// The public key the account's signatures check against.
|
||||
Uint8List get signingPublicKey => signing.publicKey;
|
||||
|
||||
/// Wipes and frees both private keys, which may not be read afterwards.
|
||||
void dispose() {
|
||||
encryption.dispose();
|
||||
signing.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// An account's private keys sealed under one key (the password's
|
||||
/// key-encryption key, or the recovery key): what the register keeps.
|
||||
final class const WrappedAccountKeys({
|
||||
/// XChaCha20-Poly1305's nonce, random.
|
||||
required final Uint8List nonce,
|
||||
|
||||
/// Both private keys, encrypted and authenticated.
|
||||
required final Uint8List cipherText,
|
||||
}) {
|
||||
/// As [toJson] wrote it; a [FormatException] otherwise.
|
||||
factory fromJson(Map<String, Object?> json) => switch (json) {
|
||||
{'nonce': final String nonce, 'cipherText': final String cipherText} =>
|
||||
WrappedAccountKeys(
|
||||
nonce: base64Decode(nonce),
|
||||
cipherText: base64Decode(cipherText),
|
||||
),
|
||||
_ => throw const FormatException('Not wrapped account keys'),
|
||||
};
|
||||
|
||||
/// As kept with the account.
|
||||
Map<String, String> toJson() => {
|
||||
'nonce': base64Encode(nonce),
|
||||
'cipherText': base64Encode(cipherText),
|
||||
};
|
||||
}
|
||||
|
||||
/// [keys]' private halves sealed under [wrappingKey] (XChaCha20-Poly1305,
|
||||
/// a random nonce), bound to their public keys, so they open only as these
|
||||
/// keys of this account.
|
||||
WrappedAccountKeys wrapAccountKeys(
|
||||
SodiumSumo sodium,
|
||||
AccountKeys keys,
|
||||
SecureKey wrappingKey,
|
||||
) {
|
||||
final aead = sodium.crypto.aeadXChaCha20Poly1305IETF;
|
||||
final nonce = sodium.randombytes.buf(aead.nonceBytes);
|
||||
// libsodium encrypts a plain buffer: the private keys are copied out of
|
||||
// guarded memory for this moment, and the copy wiped right after.
|
||||
final plainText = Uint8List.fromList([
|
||||
...keys.encryption.secretKey.extractBytes(),
|
||||
...keys.signing.secretKey.extractBytes(),
|
||||
]);
|
||||
try {
|
||||
return WrappedAccountKeys(
|
||||
nonce: nonce,
|
||||
cipherText: aead.encrypt(
|
||||
message: plainText,
|
||||
nonce: nonce,
|
||||
key: wrappingKey,
|
||||
additionalData: _boundTo(
|
||||
keys.encryptionPublicKey,
|
||||
keys.signingPublicKey,
|
||||
),
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
plainText.fillRange(0, plainText.length, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// The account's keys [wrapped] holds, opened with [wrappingKey]; refused
|
||||
/// ([KeyRefused]) for the wrong key, anything changed, or keys that aren't
|
||||
/// those of the public keys given (the register's record of the account).
|
||||
AccountKeys unwrapAccountKeys(
|
||||
SodiumSumo sodium,
|
||||
WrappedAccountKeys wrapped,
|
||||
SecureKey wrappingKey, {
|
||||
required Uint8List encryptionPublicKey,
|
||||
required Uint8List signingPublicKey,
|
||||
}) {
|
||||
if (encryptionPublicKey.length != sodium.crypto.box.publicKeyBytes ||
|
||||
signingPublicKey.length != sodium.crypto.sign.publicKeyBytes) {
|
||||
throw const KeyRefused(KeyRefusal.notTheAccountsKeys);
|
||||
}
|
||||
final Uint8List plainText;
|
||||
try {
|
||||
plainText = sodium.crypto.aeadXChaCha20Poly1305IETF.decrypt(
|
||||
cipherText: wrapped.cipherText,
|
||||
nonce: wrapped.nonce,
|
||||
key: wrappingKey,
|
||||
additionalData: _boundTo(encryptionPublicKey, signingPublicKey),
|
||||
);
|
||||
} on SodiumException {
|
||||
throw const KeyRefused(KeyRefusal.wrongKeyOrTampered);
|
||||
}
|
||||
final boxSecretBytes = sodium.crypto.box.secretKeyBytes;
|
||||
final signSecretBytes = sodium.crypto.sign.secretKeyBytes;
|
||||
try {
|
||||
if (plainText.length != boxSecretBytes + signSecretBytes) {
|
||||
throw const KeyRefused(KeyRefusal.notTheAccountsKeys);
|
||||
}
|
||||
final encryptionSecret = sodium.secureCopy(
|
||||
Uint8List.sublistView(plainText, 0, boxSecretBytes),
|
||||
);
|
||||
final signingSecret = sodium.secureCopy(
|
||||
Uint8List.sublistView(plainText, boxSecretBytes),
|
||||
);
|
||||
final keys = AccountKeys._(
|
||||
KeyPair(publicKey: encryptionPublicKey, secretKey: encryptionSecret),
|
||||
KeyPair(publicKey: signingPublicKey, secretKey: signingSecret),
|
||||
);
|
||||
// The authenticated data binds the public keys already; checking them
|
||||
// against the private halves as well costs nothing and catches a
|
||||
// wrapping made from mismatched keys.
|
||||
final derivedEncryption = sodium.crypto.scalarmult.base(
|
||||
n: encryptionSecret,
|
||||
);
|
||||
final derivedSigning = Uint8List.sublistView(
|
||||
plainText,
|
||||
plainText.length - sodium.crypto.sign.publicKeyBytes,
|
||||
);
|
||||
if (!sodium.memcmp(derivedEncryption, encryptionPublicKey) ||
|
||||
!sodium.memcmp(derivedSigning, signingPublicKey)) {
|
||||
keys.dispose();
|
||||
throw const KeyRefused(KeyRefusal.notTheAccountsKeys);
|
||||
}
|
||||
return keys;
|
||||
} finally {
|
||||
plainText.fillRange(0, plainText.length, 0);
|
||||
}
|
||||
}
|
||||
|
||||
Uint8List _boundTo(Uint8List encryptionPublicKey, Uint8List signingPublicKey) =>
|
||||
Uint8List.fromList([
|
||||
..._wrappingLabel,
|
||||
...encryptionPublicKey,
|
||||
...signingPublicKey,
|
||||
]);
|
||||
2056
packages/halkyon_keys/lib/src/bip39_english.dart
Normal file
2056
packages/halkyon_keys/lib/src/bip39_english.dart
Normal file
File diff suppressed because it is too large
Load diff
106
packages/halkyon_keys/lib/src/data_keys.dart
Normal file
106
packages/halkyon_keys/lib/src/data_keys.dart
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:halkyon_keys/src/account_keys.dart';
|
||||
import 'package:halkyon_keys/src/key_refused.dart';
|
||||
import 'package:sodium/sodium_sumo.dart';
|
||||
|
||||
/// Data keys (ADR 0017): a random key per store (Todo's agenda, a private
|
||||
/// studyset), which encrypts its content (`sealContent`) and is itself
|
||||
/// sealed to the account's public key, so every device that opens the
|
||||
/// account opens the store. Sharing a store later seals its key to the other
|
||||
/// person's key too.
|
||||
|
||||
/// A store's key, in libsodium's guarded memory until [dispose].
|
||||
final class DataKey._(
|
||||
/// Its ID, which the content it seals names (ADR 0002's `keyId`).
|
||||
final String keyId,
|
||||
|
||||
/// The key itself (XChaCha20-Poly1305's 256 bits).
|
||||
final SecureKey key,
|
||||
) {
|
||||
/// A new key named [keyId].
|
||||
factory generate(SodiumSumo sodium, String keyId) => DataKey._(
|
||||
_checkedId(keyId),
|
||||
sodium.crypto.aeadXChaCha20Poly1305IETF.keygen(),
|
||||
);
|
||||
|
||||
/// Wipes and frees the key, which may not be read afterwards.
|
||||
void dispose() => key.dispose();
|
||||
}
|
||||
|
||||
/// [dataKey] sealed to the account whose [encryptionPublicKey] it is
|
||||
/// (libsodium's sealed box: X25519 and XSalsa20-Poly1305, anonymous), its ID
|
||||
/// sealed with it, so it opens only as the key it was.
|
||||
Uint8List sealDataKey(
|
||||
SodiumSumo sodium,
|
||||
DataKey dataKey,
|
||||
Uint8List encryptionPublicKey,
|
||||
) {
|
||||
final id = utf8.encode(dataKey.keyId);
|
||||
// As account keys are wrapped, the key leaves guarded memory for this
|
||||
// moment only.
|
||||
final message = Uint8List.fromList([
|
||||
id.length,
|
||||
...id,
|
||||
...dataKey.key.extractBytes(),
|
||||
]);
|
||||
try {
|
||||
return sodium.crypto.box.seal(
|
||||
message: message,
|
||||
publicKey: encryptionPublicKey,
|
||||
);
|
||||
} finally {
|
||||
message.fillRange(0, message.length, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// The data key named [keyId] that [sealed] holds, opened with the
|
||||
/// account's [keys]; refused ([KeyRefused]) for another account's keys,
|
||||
/// anything changed, or a key sealed under another ID.
|
||||
DataKey openDataKey(
|
||||
SodiumSumo sodium,
|
||||
Uint8List sealed, {
|
||||
required String keyId,
|
||||
required AccountKeys keys,
|
||||
}) {
|
||||
final Uint8List message;
|
||||
try {
|
||||
message = sodium.crypto.box.sealOpen(
|
||||
cipherText: sealed,
|
||||
publicKey: keys.encryptionPublicKey,
|
||||
secretKey: keys.encryption.secretKey,
|
||||
);
|
||||
} on SodiumException {
|
||||
throw const KeyRefused(KeyRefusal.wrongKeyOrTampered);
|
||||
}
|
||||
try {
|
||||
final idLength = message.isEmpty ? -1 : message.first;
|
||||
final keyBytes = sodium.crypto.aeadXChaCha20Poly1305IETF.keyBytes;
|
||||
if (idLength < 0 || message.length != 1 + idLength + keyBytes) {
|
||||
throw const KeyRefused(KeyRefusal.wrongKeyOrTampered);
|
||||
}
|
||||
// The ID's bytes compared as sealed, not decoded: no two IDs match.
|
||||
final sealedId = Uint8List.sublistView(message, 1, 1 + idLength);
|
||||
final id = utf8.encode(keyId);
|
||||
if (sealedId.length != id.length || !sodium.memcmp(sealedId, id)) {
|
||||
throw const KeyRefused(KeyRefusal.wrongDataKey);
|
||||
}
|
||||
return DataKey._(
|
||||
keyId,
|
||||
sodium.secureCopy(Uint8List.sublistView(message, 1 + idLength)),
|
||||
);
|
||||
} finally {
|
||||
message.fillRange(0, message.length, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// [keyId] if it is one: 1 to 255 bytes of UTF-8, as a sealed key carries
|
||||
/// its ID's length in one byte.
|
||||
String _checkedId(String keyId) {
|
||||
final length = utf8.encode(keyId).length;
|
||||
if (length == 0 || length > 255) {
|
||||
throw ArgumentError.value(keyId, 'keyId', 'must be 1 to 255 bytes');
|
||||
}
|
||||
return keyId;
|
||||
}
|
||||
43
packages/halkyon_keys/lib/src/key_refused.dart
Normal file
43
packages/halkyon_keys/lib/src/key_refused.dart
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
/// Why something to do with an account's keys was refused: thrown, as
|
||||
/// nothing that follows may go on with a key that didn't open or a text
|
||||
/// that didn't check.
|
||||
final class const KeyRefused(
|
||||
/// Why.
|
||||
final KeyRefusal reason,
|
||||
) implements Exception {
|
||||
@override
|
||||
String toString() => 'KeyRefused(${reason.name})';
|
||||
}
|
||||
|
||||
/// Why an account's keys or what they protect were refused.
|
||||
enum KeyRefusal() {
|
||||
/// What was to be opened didn't open: the wrong key (a wrong password, a
|
||||
/// wrong recovery phrase, another account's), or it was changed since it
|
||||
/// was sealed. The two can't be told apart, by design.
|
||||
wrongKeyOrTampered,
|
||||
|
||||
/// The private keys opened, but aren't those of the public keys the
|
||||
/// account has.
|
||||
notTheAccountsKeys,
|
||||
|
||||
/// Content sealed with one data key was opened with another.
|
||||
wrongDataKey,
|
||||
|
||||
/// The author's signature doesn't check: the content was changed, or
|
||||
/// isn't the author's.
|
||||
forgedSignature,
|
||||
|
||||
/// Argon2id's costs named for an account are below what any account may
|
||||
/// have, or of another algorithm.
|
||||
weakPasswordKdf,
|
||||
|
||||
/// A recovery phrase of another length than BIP-39's.
|
||||
phraseLength,
|
||||
|
||||
/// A word of a recovery phrase isn't on BIP-39's English list.
|
||||
phraseWord,
|
||||
|
||||
/// A recovery phrase's checksum doesn't match: a word mistyped or out of
|
||||
/// order.
|
||||
phraseChecksum,
|
||||
}
|
||||
139
packages/halkyon_keys/lib/src/password_keys.dart
Normal file
139
packages/halkyon_keys/lib/src/password_keys.dart
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
import 'dart:typed_data';
|
||||
|
||||
import 'package:halkyon_keys/src/key_refused.dart';
|
||||
import 'package:sodium/sodium_sumo.dart';
|
||||
|
||||
/// The password's keys (ADR 0017): Argon2id over the password and the
|
||||
/// account's salt makes one master key, which libsodium's KDF splits into
|
||||
/// SRP's secret (from which x is made, the one value SRP takes in place of
|
||||
/// the password) and the key-encryption key that wraps the account's private
|
||||
/// keys. The password, the master key and both halves never leave the
|
||||
/// device.
|
||||
|
||||
/// libsodium's KDF context for the password's subkeys (exactly 8 bytes).
|
||||
const _passwordContext = 'hlkpass1';
|
||||
|
||||
/// The subkey that becomes SRP's x.
|
||||
final _srpSubkey = BigInt.one;
|
||||
|
||||
/// The subkey that wraps the account's private keys.
|
||||
final _keyEncryptionSubkey = BigInt.two;
|
||||
|
||||
/// How long each derived key is.
|
||||
const _keyBytes = 32;
|
||||
|
||||
/// How costly Argon2id is for an account: kept with the account (beside its
|
||||
/// salt), so the costs can be raised for new passwords without locking
|
||||
/// anyone out.
|
||||
final class const PasswordKdf({
|
||||
/// Argon2id's passes.
|
||||
required final int opsLimit,
|
||||
|
||||
/// Argon2id's memory, in bytes.
|
||||
required final int memLimit,
|
||||
}) {
|
||||
/// The costs [json] names; refused ([KeyRefused]) for another algorithm or
|
||||
/// costs below [minimum].
|
||||
factory fromJson(Map<String, Object?> json) => switch (json) {
|
||||
{
|
||||
'algorithm': 'argon2id13',
|
||||
'opsLimit': final int opsLimit,
|
||||
'memLimit': final int memLimit,
|
||||
}
|
||||
when opsLimit >= minimum.opsLimit && memLimit >= minimum.memLimit =>
|
||||
PasswordKdf(opsLimit: opsLimit, memLimit: memLimit),
|
||||
_ => throw const KeyRefused(KeyRefusal.weakPasswordKdf),
|
||||
};
|
||||
|
||||
/// The floor no account's costs may go below: a register sending lower
|
||||
/// costs would make every guess cheaper. Raised only once no account is
|
||||
/// below it any more, or those accounts no longer open.
|
||||
static const minimum = PasswordKdf(opsLimit: 3, memLimit: 64 * 1024 * 1024);
|
||||
|
||||
/// What new passwords take: 64 MiB and 3 passes, a second or so on a
|
||||
/// phone. Raising it leaves accounts made before at their own costs, at
|
||||
/// or above [minimum].
|
||||
static const current = minimum;
|
||||
|
||||
/// The costs as kept with the account.
|
||||
Map<String, Object> toJson() => {
|
||||
'algorithm': 'argon2id13',
|
||||
'opsLimit': opsLimit,
|
||||
'memLimit': memLimit,
|
||||
};
|
||||
}
|
||||
|
||||
/// A new salt for an account's password: libsodium's 16 random bytes.
|
||||
Uint8List newPasswordSalt(SodiumSumo sodium) =>
|
||||
sodium.randombytes.buf(sodium.crypto.pwhash.saltBytes);
|
||||
|
||||
/// What the password unlocks, held in libsodium's guarded memory until
|
||||
/// [dispose].
|
||||
final class PasswordKeys._(
|
||||
/// The subkey SRP's x is made of ([srpPrivateValue]).
|
||||
final SecureKey srpSecret,
|
||||
|
||||
/// The key that wraps the account's private keys.
|
||||
final SecureKey keyEncryptionKey,
|
||||
) {
|
||||
/// The number x SRP takes in place of the password: the SRP subkey's 256
|
||||
/// bits, big-endian. It is the password's Argon2id in all but name, so a
|
||||
/// verifier made from it costs an Argon2id per guess.
|
||||
BigInt get srpPrivateValue => srpSecret.runUnlockedSync((bytes) {
|
||||
var value = BigInt.zero;
|
||||
for (final byte in bytes) {
|
||||
value = (value << 8) | BigInt.from(byte);
|
||||
}
|
||||
return value;
|
||||
});
|
||||
|
||||
/// Wipes and frees both keys; neither may be read afterwards (libsodium
|
||||
/// has freed their memory).
|
||||
void dispose() {
|
||||
srpSecret.dispose();
|
||||
keyEncryptionKey.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// The keys [password] unlocks for the account with [salt], at the costs
|
||||
/// [kdf] names (the account's own; [PasswordKdf.current] for a new one).
|
||||
PasswordKeys derivePasswordKeys(
|
||||
SodiumSumo sodium, {
|
||||
required String password,
|
||||
required Uint8List salt,
|
||||
PasswordKdf kdf = PasswordKdf.current,
|
||||
}) {
|
||||
if (salt.length != sodium.crypto.pwhash.saltBytes) {
|
||||
throw ArgumentError.value(
|
||||
salt.length,
|
||||
'salt',
|
||||
'must be ${sodium.crypto.pwhash.saltBytes} bytes',
|
||||
);
|
||||
}
|
||||
final masterKey = sodium.crypto.pwhash.callStr(
|
||||
outLen: _keyBytes,
|
||||
password: password,
|
||||
salt: salt,
|
||||
opsLimit: kdf.opsLimit,
|
||||
memLimit: kdf.memLimit,
|
||||
alg: CryptoPwhashAlgorithm.argon2id13,
|
||||
);
|
||||
try {
|
||||
return PasswordKeys._(
|
||||
sodium.crypto.kdf.deriveFromKey(
|
||||
masterKey: masterKey,
|
||||
context: _passwordContext,
|
||||
subkeyId: _srpSubkey,
|
||||
subkeyLen: _keyBytes,
|
||||
),
|
||||
sodium.crypto.kdf.deriveFromKey(
|
||||
masterKey: masterKey,
|
||||
context: _passwordContext,
|
||||
subkeyId: _keyEncryptionSubkey,
|
||||
subkeyLen: _keyBytes,
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
masterKey.dispose();
|
||||
}
|
||||
}
|
||||
153
packages/halkyon_keys/lib/src/recovery_phrase.dart
Normal file
153
packages/halkyon_keys/lib/src/recovery_phrase.dart
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
import 'dart:typed_data';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:halkyon_keys/src/bip39_english.dart';
|
||||
import 'package:halkyon_keys/src/key_refused.dart';
|
||||
import 'package:sodium/sodium_sumo.dart';
|
||||
|
||||
/// The recovery phrase (ADR 0017): 24 words of BIP-39's English list for
|
||||
/// 256 random bits and an 8-bit checksum, written down by the person at
|
||||
/// sign-up. Its bits make the recovery key, which wraps the account's
|
||||
/// private keys a second time: with the phrase, a lost password keeps
|
||||
/// everything. The phrase never leaves the device it is typed into.
|
||||
|
||||
/// libsodium's KDF context for the recovery key (exactly 8 bytes).
|
||||
const _recoveryContext = 'hlkrcvy1';
|
||||
|
||||
/// How many random bytes a new phrase stands for: 256 bits, 24 words.
|
||||
const recoveryEntropyBytes = 32;
|
||||
|
||||
/// A new phrase from [recoveryEntropyBytes] random bytes.
|
||||
String newRecoveryPhrase(SodiumSumo sodium) {
|
||||
final entropy = sodium.randombytes.buf(recoveryEntropyBytes);
|
||||
try {
|
||||
return recoveryPhraseOf(entropy);
|
||||
} finally {
|
||||
entropy.fillRange(0, entropy.length, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// BIP-39's mnemonic for [entropy] (16 to 32 bytes, a multiple of 4): the
|
||||
/// entropy, then the first entropy-bits ÷ 32 bits of its SHA-256, read as
|
||||
/// 11-bit indexes into the English list.
|
||||
String recoveryPhraseOf(List<int> entropy) {
|
||||
if (entropy.length < 16 || entropy.length > 32 || entropy.length % 4 != 0) {
|
||||
throw ArgumentError.value(
|
||||
entropy.length,
|
||||
'entropy',
|
||||
'must be 16 to 32 bytes, a multiple of 4',
|
||||
);
|
||||
}
|
||||
final checksumBits = entropy.length * 8 ~/ 32;
|
||||
final bits = [
|
||||
..._bitsOf(entropy),
|
||||
..._bitsOf(sha256.convert(entropy).bytes).take(checksumBits),
|
||||
];
|
||||
return [
|
||||
for (var i = 0; i < bits.length; i += 11)
|
||||
bip39English[bits
|
||||
.sublist(i, i + 11)
|
||||
.fold(0, (index, bit) => (index << 1) | bit)],
|
||||
].join(' ');
|
||||
}
|
||||
|
||||
/// The entropy [phrase] stands for, its checksum checked; refused
|
||||
/// ([KeyRefused]) for a length BIP-39 doesn't have, a word not on the
|
||||
/// English list, or a checksum that doesn't match. Case and the spaces
|
||||
/// between words don't matter.
|
||||
Uint8List entropyOfRecoveryPhrase(String phrase) {
|
||||
final words = phrase.trim().toLowerCase().split(RegExp(r'\s+'));
|
||||
if (!const {12, 15, 18, 21, 24}.contains(words.length)) {
|
||||
throw const KeyRefused(KeyRefusal.phraseLength);
|
||||
}
|
||||
final bits = <int>[];
|
||||
for (final word in words) {
|
||||
final index = _indexOf(word);
|
||||
if (index == null) {
|
||||
throw const KeyRefused(KeyRefusal.phraseWord);
|
||||
}
|
||||
for (var shift = 10; shift >= 0; shift--) {
|
||||
bits.add((index >> shift) & 1);
|
||||
}
|
||||
}
|
||||
final checksumBits = bits.length ~/ 33;
|
||||
final entropyBits = bits.length - checksumBits;
|
||||
final entropy = Uint8List(entropyBits ~/ 8);
|
||||
for (var i = 0; i < entropy.length; i++) {
|
||||
entropy[i] = bits
|
||||
.sublist(i * 8, i * 8 + 8)
|
||||
.fold(0, (byte, bit) => (byte << 1) | bit);
|
||||
}
|
||||
final expected = _bitsOf(sha256.convert(entropy).bytes).take(checksumBits);
|
||||
if (!_sameBits(bits.sublist(entropyBits), expected.toList())) {
|
||||
entropy.fillRange(0, entropy.length, 0);
|
||||
throw const KeyRefused(KeyRefusal.phraseChecksum);
|
||||
}
|
||||
return entropy;
|
||||
}
|
||||
|
||||
/// The recovery key [phrase] stands for: its 256 random bits through
|
||||
/// libsodium's KDF, in guarded memory. Refused as
|
||||
/// [entropyOfRecoveryPhrase] refuses, and for a phrase of fewer than 256
|
||||
/// bits (recovery phrases are 24 words).
|
||||
SecureKey recoveryKeyOf(SodiumSumo sodium, String phrase) {
|
||||
final entropy = entropyOfRecoveryPhrase(phrase);
|
||||
try {
|
||||
if (entropy.length != recoveryEntropyBytes) {
|
||||
throw const KeyRefused(KeyRefusal.phraseLength);
|
||||
}
|
||||
final master = sodium.secureCopy(entropy);
|
||||
try {
|
||||
return sodium.crypto.kdf.deriveFromKey(
|
||||
masterKey: master,
|
||||
context: _recoveryContext,
|
||||
subkeyId: BigInt.one,
|
||||
subkeyLen: 32,
|
||||
);
|
||||
} finally {
|
||||
master.dispose();
|
||||
}
|
||||
} finally {
|
||||
entropy.fillRange(0, entropy.length, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// [bytes] as bits, most significant first.
|
||||
Iterable<int> _bitsOf(List<int> bytes) sync* {
|
||||
for (final byte in bytes) {
|
||||
for (var shift = 7; shift >= 0; shift--) {
|
||||
yield (byte >> shift) & 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool _sameBits(List<int> a, List<int> b) {
|
||||
if (a.length != b.length) {
|
||||
return false;
|
||||
}
|
||||
var difference = 0;
|
||||
for (var i = 0; i < a.length; i++) {
|
||||
difference |= a[i] ^ b[i];
|
||||
}
|
||||
return difference == 0;
|
||||
}
|
||||
|
||||
/// [word]'s index in the English list (sorted, so found by halving), or
|
||||
/// null.
|
||||
int? _indexOf(String word) {
|
||||
var low = 0;
|
||||
var high = bip39English.length - 1;
|
||||
while (low <= high) {
|
||||
final middle = (low + high) ~/ 2;
|
||||
final order = bip39English[middle].compareTo(word);
|
||||
if (order == 0) {
|
||||
return middle;
|
||||
}
|
||||
if (order < 0) {
|
||||
low = middle + 1;
|
||||
} else {
|
||||
high = middle - 1;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
123
packages/halkyon_keys/lib/src/sealed_content.dart
Normal file
123
packages/halkyon_keys/lib/src/sealed_content.dart
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:halkyon_keys/src/account_keys.dart';
|
||||
import 'package:halkyon_keys/src/data_keys.dart';
|
||||
import 'package:halkyon_keys/src/key_refused.dart';
|
||||
import 'package:sodium/sodium_sumo.dart';
|
||||
|
||||
/// Content sealed for the people who hold a store's data key (ADR 0017), in
|
||||
/// ADR 0002's envelope: the key's ID, a random nonce, and the encrypted
|
||||
/// payload (XChaCha20-Poly1305), with its author's Ed25519 signature beside.
|
||||
///
|
||||
/// The authenticated data and the signature both take a `context` the
|
||||
/// caller names: what the content is (its table and row, say), so a server
|
||||
/// can't move one row's sealed content into another's place unnoticed.
|
||||
|
||||
/// The version both the authenticated data and the signature start with.
|
||||
final _contentLabel = utf8.encode('halkyon content v1');
|
||||
|
||||
/// What a store's content becomes: ADR 0002's `keyId`, `nonce` and
|
||||
/// `payload`, and the author's [signature].
|
||||
final class const SealedContent({
|
||||
/// The data key's ID.
|
||||
required final String keyId,
|
||||
|
||||
/// XChaCha20-Poly1305's nonce, random for every sealing.
|
||||
required final Uint8List nonce,
|
||||
|
||||
/// The encrypted content.
|
||||
required final Uint8List payload,
|
||||
|
||||
/// The author's detached Ed25519 signature over all of it.
|
||||
required final Uint8List signature,
|
||||
});
|
||||
|
||||
/// [plainText] sealed with [dataKey], signed by [author], for the
|
||||
/// [context] it is stored in.
|
||||
SealedContent sealContent(
|
||||
SodiumSumo sodium, {
|
||||
required Uint8List plainText,
|
||||
required DataKey dataKey,
|
||||
required AccountKeys author,
|
||||
required List<int> context,
|
||||
}) {
|
||||
final aead = sodium.crypto.aeadXChaCha20Poly1305IETF;
|
||||
final nonce = sodium.randombytes.buf(aead.nonceBytes);
|
||||
final payload = aead.encrypt(
|
||||
message: plainText,
|
||||
nonce: nonce,
|
||||
key: dataKey.key,
|
||||
additionalData: _framed([utf8.encode(dataKey.keyId), context]),
|
||||
);
|
||||
return SealedContent(
|
||||
keyId: dataKey.keyId,
|
||||
nonce: nonce,
|
||||
payload: payload,
|
||||
signature: sodium.crypto.sign.detached(
|
||||
message: _signed(dataKey.keyId, nonce, payload, context),
|
||||
secretKey: author.signing.secretKey,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// What [sealed] holds, its signature checked against the author's
|
||||
/// [authorSigningPublicKey] first, then opened with [dataKey] for the
|
||||
/// [context] it is stored in; refused ([KeyRefused]) for another data key,
|
||||
/// a signature that doesn't check (changed, or someone else's), or content
|
||||
/// that doesn't open.
|
||||
Uint8List openContent(
|
||||
SodiumSumo sodium,
|
||||
SealedContent sealed, {
|
||||
required DataKey dataKey,
|
||||
required Uint8List authorSigningPublicKey,
|
||||
required List<int> context,
|
||||
}) {
|
||||
if (sealed.keyId != dataKey.keyId) {
|
||||
throw const KeyRefused(KeyRefusal.wrongDataKey);
|
||||
}
|
||||
if (sealed.signature.length != sodium.crypto.sign.bytes ||
|
||||
authorSigningPublicKey.length != sodium.crypto.sign.publicKeyBytes ||
|
||||
!sodium.crypto.sign.verifyDetached(
|
||||
message: _signed(sealed.keyId, sealed.nonce, sealed.payload, context),
|
||||
signature: sealed.signature,
|
||||
publicKey: authorSigningPublicKey,
|
||||
)) {
|
||||
throw const KeyRefused(KeyRefusal.forgedSignature);
|
||||
}
|
||||
final aead = sodium.crypto.aeadXChaCha20Poly1305IETF;
|
||||
if (sealed.nonce.length != aead.nonceBytes) {
|
||||
throw const KeyRefused(KeyRefusal.wrongKeyOrTampered);
|
||||
}
|
||||
try {
|
||||
return aead.decrypt(
|
||||
cipherText: sealed.payload,
|
||||
nonce: sealed.nonce,
|
||||
key: dataKey.key,
|
||||
additionalData: _framed([utf8.encode(sealed.keyId), context]),
|
||||
);
|
||||
} on SodiumException {
|
||||
throw const KeyRefused(KeyRefusal.wrongKeyOrTampered);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the author signs: the label, then the key's ID, the nonce, the
|
||||
/// payload and the context, each with its length.
|
||||
Uint8List _signed(
|
||||
String keyId,
|
||||
Uint8List nonce,
|
||||
Uint8List payload,
|
||||
List<int> context,
|
||||
) => _framed([utf8.encode(keyId), nonce, payload, context]);
|
||||
|
||||
/// [parts] after the label, each led by its length in four bytes, so no two
|
||||
/// sequences of parts frame alike.
|
||||
Uint8List _framed(List<List<int>> parts) {
|
||||
final out = BytesBuilder(copy: false)..add(_contentLabel);
|
||||
for (final part in parts) {
|
||||
out
|
||||
..add((ByteData(4)..setUint32(0, part.length)).buffer.asUint8List())
|
||||
..add(part);
|
||||
}
|
||||
return out.toBytes();
|
||||
}
|
||||
26
packages/halkyon_keys/pubspec.yaml
Normal file
26
packages/halkyon_keys/pubspec.yaml
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
name: halkyon_keys
|
||||
description: >-
|
||||
An account's keys on the device (ADR 0017): the password's Argon2id key and
|
||||
what it splits into, the account's key pairs and their wrapping, the recovery
|
||||
phrase, data keys sealed to the account, and content encrypted and signed in
|
||||
ADR 0002's envelope. libsodium does every primitive.
|
||||
version: 0.1.0
|
||||
publish_to: none
|
||||
resolution: workspace
|
||||
|
||||
environment:
|
||||
sdk: ^3.13.0
|
||||
|
||||
dependencies:
|
||||
# SHA-256, which BIP-39's checksum is made with.
|
||||
crypto: ^3.0.7
|
||||
# libsodium's API (Argon2id, X25519, Ed25519, XChaCha20-Poly1305, sealed
|
||||
# boxes, the KDF), pinned exactly: what keys an account's data must never
|
||||
# move by accident. Its build hook compiles libsodium 1.0.22 from the source
|
||||
# it ships (no download; a C compiler and make on every machine that builds),
|
||||
# which replaced sodium_libs's prebuilt binaries. 4.1.0+1, as 4.1.1 on needs
|
||||
# code_assets 2, which Learn's mecab_for_dart (2.0.5) doesn't allow yet.
|
||||
sodium: 4.1.0+1
|
||||
|
||||
dev_dependencies:
|
||||
test: ^1.31.1
|
||||
198
packages/halkyon_keys/test/account_keys_test.dart
Normal file
198
packages/halkyon_keys/test/account_keys_test.dart
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
import 'dart:typed_data';
|
||||
|
||||
import 'package:halkyon_keys/halkyon_keys.dart';
|
||||
import 'package:sodium/sodium_sumo.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
Future<void> main() async {
|
||||
final sodium = await SodiumSumoInit.init();
|
||||
const cheap = PasswordKdf(opsLimit: 1, memLimit: 8192);
|
||||
final salt = Uint8List.fromList(List.generate(16, (i) => i));
|
||||
|
||||
Matcher refusedFor(KeyRefusal reason) => throwsA(
|
||||
isA<KeyRefused>().having((refused) => refused.reason, 'reason', reason),
|
||||
);
|
||||
|
||||
test('key pairs: X25519 to encrypt to, Ed25519 to sign with', () {
|
||||
final keys = AccountKeys.generate(sodium);
|
||||
expect(keys.encryptionPublicKey, hasLength(32));
|
||||
expect(keys.signingPublicKey, hasLength(32));
|
||||
expect(
|
||||
AccountKeys.generate(sodium).encryptionPublicKey,
|
||||
isNot(keys.encryptionPublicKey),
|
||||
);
|
||||
});
|
||||
|
||||
group('wrapped under the password', () {
|
||||
final keys = AccountKeys.generate(sodium);
|
||||
final password = derivePasswordKeys(
|
||||
sodium,
|
||||
password: 'a password',
|
||||
salt: salt,
|
||||
kdf: cheap,
|
||||
);
|
||||
final wrapped = wrapAccountKeys(sodium, keys, password.keyEncryptionKey);
|
||||
|
||||
AccountKeys unwrap(
|
||||
WrappedAccountKeys what,
|
||||
SecureKey key, {
|
||||
Uint8List? encryptionPublicKey,
|
||||
Uint8List? signingPublicKey,
|
||||
}) => unwrapAccountKeys(
|
||||
sodium,
|
||||
what,
|
||||
key,
|
||||
encryptionPublicKey: encryptionPublicKey ?? keys.encryptionPublicKey,
|
||||
signingPublicKey: signingPublicKey ?? keys.signingPublicKey,
|
||||
);
|
||||
|
||||
test('the same password opens them on another device, the same keys', () {
|
||||
final again = derivePasswordKeys(
|
||||
sodium,
|
||||
password: 'a password',
|
||||
salt: salt,
|
||||
kdf: cheap,
|
||||
);
|
||||
final opened = unwrap(
|
||||
WrappedAccountKeys.fromJson(wrapped.toJson()),
|
||||
again.keyEncryptionKey,
|
||||
);
|
||||
expect(
|
||||
opened.encryption.secretKey.extractBytes(),
|
||||
keys.encryption.secretKey.extractBytes(),
|
||||
);
|
||||
expect(
|
||||
opened.signing.secretKey.extractBytes(),
|
||||
keys.signing.secretKey.extractBytes(),
|
||||
);
|
||||
// They work: a signature made with the opened key checks.
|
||||
final message = Uint8List.fromList([1, 2, 3]);
|
||||
expect(
|
||||
sodium.crypto.sign.verifyDetached(
|
||||
message: message,
|
||||
signature: sodium.crypto.sign.detached(
|
||||
message: message,
|
||||
secretKey: opened.signing.secretKey,
|
||||
),
|
||||
publicKey: keys.signingPublicKey,
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
|
||||
test('nothing secret is in what the register keeps', () {
|
||||
final json = wrapped.toJson();
|
||||
expect(json.keys, unorderedEquals(['nonce', 'cipherText']));
|
||||
expect(wrapped.nonce, hasLength(24));
|
||||
// 32 + 64 bytes of keys and Poly1305's 16-byte tag.
|
||||
expect(wrapped.cipherText, hasLength(112));
|
||||
});
|
||||
|
||||
test('a wrong password is refused', () {
|
||||
final wrong = derivePasswordKeys(
|
||||
sodium,
|
||||
password: 'a passwort',
|
||||
salt: salt,
|
||||
kdf: cheap,
|
||||
);
|
||||
expect(
|
||||
() => unwrap(wrapped, wrong.keyEncryptionKey),
|
||||
refusedFor(KeyRefusal.wrongKeyOrTampered),
|
||||
);
|
||||
});
|
||||
|
||||
test('a ciphertext or nonce changed is refused', () {
|
||||
final cipherText = Uint8List.fromList(wrapped.cipherText)..[5] ^= 1;
|
||||
final nonce = Uint8List.fromList(wrapped.nonce)..[0] ^= 1;
|
||||
for (final tampered in [
|
||||
WrappedAccountKeys(nonce: wrapped.nonce, cipherText: cipherText),
|
||||
WrappedAccountKeys(nonce: nonce, cipherText: wrapped.cipherText),
|
||||
WrappedAccountKeys(
|
||||
nonce: wrapped.nonce,
|
||||
cipherText: wrapped.cipherText.sublist(1),
|
||||
),
|
||||
]) {
|
||||
expect(
|
||||
() => unwrap(tampered, password.keyEncryptionKey),
|
||||
refusedFor(KeyRefusal.wrongKeyOrTampered),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("another account's public keys don't open them: they are bound to "
|
||||
'their own', () {
|
||||
final other = AccountKeys.generate(sodium);
|
||||
expect(
|
||||
() => unwrap(
|
||||
wrapped,
|
||||
password.keyEncryptionKey,
|
||||
encryptionPublicKey: other.encryptionPublicKey,
|
||||
),
|
||||
refusedFor(KeyRefusal.wrongKeyOrTampered),
|
||||
);
|
||||
expect(
|
||||
() => unwrap(
|
||||
wrapped,
|
||||
password.keyEncryptionKey,
|
||||
signingPublicKey: other.signingPublicKey,
|
||||
),
|
||||
refusedFor(KeyRefusal.wrongKeyOrTampered),
|
||||
);
|
||||
expect(
|
||||
() => unwrap(
|
||||
wrapped,
|
||||
password.keyEncryptionKey,
|
||||
signingPublicKey: Uint8List(31),
|
||||
),
|
||||
refusedFor(KeyRefusal.notTheAccountsKeys),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('wrapped again under the recovery key, the phrase opens them', () {
|
||||
final keys = AccountKeys.generate(sodium);
|
||||
final phrase = newRecoveryPhrase(sodium);
|
||||
final wrapped = wrapAccountKeys(
|
||||
sodium,
|
||||
keys,
|
||||
recoveryKeyOf(sodium, phrase),
|
||||
);
|
||||
final opened = unwrapAccountKeys(
|
||||
sodium,
|
||||
wrapped,
|
||||
recoveryKeyOf(sodium, phrase),
|
||||
encryptionPublicKey: keys.encryptionPublicKey,
|
||||
signingPublicKey: keys.signingPublicKey,
|
||||
);
|
||||
expect(
|
||||
opened.encryption.secretKey.extractBytes(),
|
||||
keys.encryption.secretKey.extractBytes(),
|
||||
);
|
||||
expect(
|
||||
() => unwrapAccountKeys(
|
||||
sodium,
|
||||
wrapped,
|
||||
recoveryKeyOf(sodium, newRecoveryPhrase(sodium)),
|
||||
encryptionPublicKey: keys.encryptionPublicKey,
|
||||
signingPublicKey: keys.signingPublicKey,
|
||||
),
|
||||
refusedFor(KeyRefusal.wrongKeyOrTampered),
|
||||
);
|
||||
});
|
||||
|
||||
test('every wrapping takes a new nonce', () {
|
||||
final keys = AccountKeys.generate(sodium);
|
||||
final key = sodium.crypto.aeadXChaCha20Poly1305IETF.keygen();
|
||||
final first = wrapAccountKeys(sodium, keys, key);
|
||||
final second = wrapAccountKeys(sodium, keys, key);
|
||||
expect(first.nonce, isNot(second.nonce));
|
||||
expect(first.cipherText, isNot(second.cipherText));
|
||||
});
|
||||
|
||||
test("what isn't wrapped account keys can't be read as such", () {
|
||||
expect(
|
||||
() => WrappedAccountKeys.fromJson({'nonce': 'AAAA'}),
|
||||
throwsFormatException,
|
||||
);
|
||||
});
|
||||
}
|
||||
90
packages/halkyon_keys/test/argon2id_test.dart
Normal file
90
packages/halkyon_keys/test/argon2id_test.dart
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
import 'dart:typed_data';
|
||||
|
||||
import 'package:sodium/sodium_sumo.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
/// [hex] as bytes.
|
||||
Uint8List _bytes(String hex) => Uint8List.fromList([
|
||||
for (var i = 0; i < hex.length; i += 2)
|
||||
int.parse(hex.substring(i, i + 2), radix: 16),
|
||||
]);
|
||||
|
||||
/// [bytes] in lower-case hex.
|
||||
String _hex(List<int> bytes) =>
|
||||
bytes.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join();
|
||||
|
||||
Future<void> main() async {
|
||||
final sodium = await SodiumSumoInit.init();
|
||||
|
||||
// libsodium's own known answers for crypto_pwhash with Argon2id
|
||||
// (libsodium 1.0.18, test/default/pwhash_argon2id.c's tv(), vectors 0
|
||||
// and 6, and their lines 1 and 7 of pwhash_argon2id.exp): the password
|
||||
// and salt as the test cuts them (the password to its length, the salt
|
||||
// to 16 bytes), the output length, the passes and the memory.
|
||||
const vectors =
|
||||
<
|
||||
({
|
||||
String password,
|
||||
int length,
|
||||
String salt,
|
||||
int outLen,
|
||||
int opsLimit,
|
||||
int memLimit,
|
||||
String expected,
|
||||
})
|
||||
>[
|
||||
(
|
||||
password:
|
||||
'a347ae92bce9f80f6f595a4480fc9c2fe7e7d7148d371e9487d75f5c23008ffa'
|
||||
'e065577a928febd9b1973a5a95073acdbeb6a030cfc0d79caa2dc5cd011cef02'
|
||||
'c08da232d76d52dfbca38ca8dcbd665b17d1665f7cf5fe59772ec909733b24de'
|
||||
'97d6f58d220b20c60d7c07ec1fd93c52c31020300c6c1facd77937a597c7a6',
|
||||
length: 127,
|
||||
salt: '5541fbc995d5c197ba290346d2c559de',
|
||||
outLen: 155,
|
||||
opsLimit: 5,
|
||||
memLimit: 7256678,
|
||||
expected:
|
||||
'18acec5d6507739f203d1f5d9f1d862f7c2cdac4f19d2bdff64487e60d969e3c'
|
||||
'ed615337b9eec6ac4461c6ca07f0939741e57c24d0005c7ea171a0ee1e734824'
|
||||
'9d135b38f222e4dad7b9a033ed83f5ca27277393e316582033c74affe2566a2b'
|
||||
'ea47f91f0fd9fe49ece7e1f79f3ad6e9b23e0277c8ecc4b313225748dd2a80f5'
|
||||
'679534a0700e246a79a49b3f74eb89ec6205fe1eeb941c73b1fcf1',
|
||||
),
|
||||
(
|
||||
password:
|
||||
'b540beb016a5366524d4605156493f9874514a5aa58818cd0c6dfffaa9e90205'
|
||||
'f17b',
|
||||
length: 34,
|
||||
salt: '44071f6d181561670bda728d43fb79b4',
|
||||
outLen: 231,
|
||||
opsLimit: 1,
|
||||
memLimit: 1631659,
|
||||
expected:
|
||||
'7fb72409b0987f8190c3729710e98c3f80c5a8727d425fdcde7f3644d467fe97'
|
||||
'3f5b5fee683bd3fce812cb9ae5e9921a2d06c2f1905e4e839692f2b934b682f1'
|
||||
'1a2fe2b90482ea5dd234863516dba6f52dc0702d324ec77d860c2e181f84472b'
|
||||
'd7104fedce071ffa93c5309494ad51623d214447a7b2b1462dc7d5d55a1f6fd5'
|
||||
'b54ce024118d86f0c6489d16545aaa87b6689dad9f2fb47fda9894f8e12b87d9'
|
||||
'78b483ccd4cc5fd9595cdc7a818452f915ce2f7df95ec12b1c72e3788d473441'
|
||||
'd884f9748eb14703c21b45d82fd667b85f5b2d98c13303b3fe76285531a826b6'
|
||||
'fc0fe8e3dddecf',
|
||||
),
|
||||
];
|
||||
|
||||
for (final (index, vector) in vectors.indexed) {
|
||||
test("Argon2id gives libsodium's known answer $index", () {
|
||||
final key = sodium.crypto.pwhash.callRaw(
|
||||
outLen: vector.outLen,
|
||||
password: Int8List.fromList(_bytes(vector.password)),
|
||||
salt: _bytes(vector.salt),
|
||||
opsLimit: vector.opsLimit,
|
||||
memLimit: vector.memLimit,
|
||||
alg: CryptoPwhashAlgorithm.argon2id13,
|
||||
);
|
||||
expect(_bytes(vector.password), hasLength(vector.length));
|
||||
expect(_hex(key.extractBytes()), vector.expected);
|
||||
key.dispose();
|
||||
});
|
||||
}
|
||||
}
|
||||
102
packages/halkyon_keys/test/bip39_vectors.dart
Normal file
102
packages/halkyon_keys/test/bip39_vectors.dart
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
// BIP-39's English test vectors (trezor/python-mnemonic, vectors.json, MIT
|
||||
// License): the entropy and the mnemonic it makes.
|
||||
|
||||
/// (entropy in hex, mnemonic).
|
||||
const bip39Vectors = <(String, String)>[
|
||||
(
|
||||
'00000000000000000000000000000000',
|
||||
'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about',
|
||||
),
|
||||
(
|
||||
'7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f',
|
||||
'legal winner thank year wave sausage worth useful legal winner thank yellow',
|
||||
),
|
||||
(
|
||||
'80808080808080808080808080808080',
|
||||
'letter advice cage absurd amount doctor acoustic avoid letter advice cage above',
|
||||
),
|
||||
(
|
||||
'ffffffffffffffffffffffffffffffff',
|
||||
'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong',
|
||||
),
|
||||
(
|
||||
'000000000000000000000000000000000000000000000000',
|
||||
'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon agent',
|
||||
),
|
||||
(
|
||||
'7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f',
|
||||
'legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal will',
|
||||
),
|
||||
(
|
||||
'808080808080808080808080808080808080808080808080',
|
||||
'letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter always',
|
||||
),
|
||||
(
|
||||
'ffffffffffffffffffffffffffffffffffffffffffffffff',
|
||||
'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo when',
|
||||
),
|
||||
(
|
||||
'0000000000000000000000000000000000000000000000000000000000000000',
|
||||
'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art',
|
||||
),
|
||||
(
|
||||
'7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f',
|
||||
'legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth title',
|
||||
),
|
||||
(
|
||||
'8080808080808080808080808080808080808080808080808080808080808080',
|
||||
'letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic bless',
|
||||
),
|
||||
(
|
||||
'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff',
|
||||
'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo vote',
|
||||
),
|
||||
(
|
||||
'9e885d952ad362caeb4efe34a8e91bd2',
|
||||
'ozone drill grab fiber curtain grace pudding thank cruise elder eight picnic',
|
||||
),
|
||||
(
|
||||
'6610b25967cdcca9d59875f5cb50b0ea75433311869e930b',
|
||||
'gravity machine north sort system female filter attitude volume fold club stay feature office ecology stable narrow fog',
|
||||
),
|
||||
(
|
||||
'68a79eaca2324873eacc50cb9c6eca8cc68ea5d936f98787c60c7ebc74e6ce7c',
|
||||
'hamster diagram private dutch cause delay private meat slide toddler razor book happy fancy gospel tennis maple dilemma loan word shrug inflict delay length',
|
||||
),
|
||||
(
|
||||
'c0ba5a8e914111210f2bd131f3d5e08d',
|
||||
'scheme spot photo card baby mountain device kick cradle pact join borrow',
|
||||
),
|
||||
(
|
||||
'6d9be1ee6ebd27a258115aad99b7317b9c8d28b6d76431c3',
|
||||
'horn tenant knee talent sponsor spell gate clip pulse soap slush warm silver nephew swap uncle crack brave',
|
||||
),
|
||||
(
|
||||
'9f6a2878b2520799a44ef18bc7df394e7061a224d2c33cd015b157d746869863',
|
||||
'panda eyebrow bullet gorilla call smoke muffin taste mesh discover soft ostrich alcohol speed nation flash devote level hobby quick inner drive ghost inside',
|
||||
),
|
||||
(
|
||||
'23db8160a31d3e0dca3688ed941adbf3',
|
||||
'cat swing flag economy stadium alone churn speed unique patch report train',
|
||||
),
|
||||
(
|
||||
'8197a4a47f0425faeaa69deebc05ca29c0a5b5cc76ceacc0',
|
||||
'light rule cinnamon wrap drastic word pride squirrel upgrade then income fatal apart sustain crack supply proud access',
|
||||
),
|
||||
(
|
||||
'066dca1a2bb7e8a1db2832148ce9933eea0f3ac9548d793112d9a95c9407efad',
|
||||
'all hour make first leader extend hole alien behind guard gospel lava path output census museum junior mass reopen famous sing advance salt reform',
|
||||
),
|
||||
(
|
||||
'f30f8c1da665478f49b001d94c5fc452',
|
||||
'vessel ladder alter error federal sibling chat ability sun glass valve picture',
|
||||
),
|
||||
(
|
||||
'c10ec20dc3cd9f652c7fac2f1230f7a3c828389a14392f05',
|
||||
'scissors invite lock maple supreme raw rapid void congress muscle digital elegant little brisk hair mango congress clump',
|
||||
),
|
||||
(
|
||||
'f585c11aec520db57dd353c69554b21a89b20fb0650966fa0a9d6f74fd989d8f',
|
||||
'void come effort suffer camp survey warrior heavy shoot primary clutch crush open amazing screen patrol group space point ten exist slush involve unfold',
|
||||
),
|
||||
];
|
||||
197
packages/halkyon_keys/test/data_keys_and_content_test.dart
Normal file
197
packages/halkyon_keys/test/data_keys_and_content_test.dart
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:halkyon_keys/halkyon_keys.dart';
|
||||
import 'package:sodium/sodium_sumo.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
Future<void> main() async {
|
||||
final sodium = await SodiumSumoInit.init();
|
||||
|
||||
Matcher refusedFor(KeyRefusal reason) => throwsA(
|
||||
isA<KeyRefused>().having((refused) => refused.reason, 'reason', reason),
|
||||
);
|
||||
|
||||
group('data keys, sealed to the account', () {
|
||||
final account = AccountKeys.generate(sodium);
|
||||
final dataKey = DataKey.generate(sodium, 'agenda-2026');
|
||||
final sealed = sealDataKey(sodium, dataKey, account.encryptionPublicKey);
|
||||
|
||||
test("any device that opens the account opens the store's key", () {
|
||||
final opened = openDataKey(
|
||||
sodium,
|
||||
sealed,
|
||||
keyId: 'agenda-2026',
|
||||
keys: account,
|
||||
);
|
||||
expect(opened.keyId, 'agenda-2026');
|
||||
expect(opened.key.extractBytes(), dataKey.key.extractBytes());
|
||||
});
|
||||
|
||||
test("another account's keys don't open it", () {
|
||||
expect(
|
||||
() => openDataKey(
|
||||
sodium,
|
||||
sealed,
|
||||
keyId: 'agenda-2026',
|
||||
keys: AccountKeys.generate(sodium),
|
||||
),
|
||||
refusedFor(KeyRefusal.wrongKeyOrTampered),
|
||||
);
|
||||
});
|
||||
|
||||
test('a sealed key changed is refused', () {
|
||||
final tampered = Uint8List.fromList(sealed)..[40] ^= 1;
|
||||
expect(
|
||||
() => openDataKey(
|
||||
sodium,
|
||||
tampered,
|
||||
keyId: 'agenda-2026',
|
||||
keys: account,
|
||||
),
|
||||
refusedFor(KeyRefusal.wrongKeyOrTampered),
|
||||
);
|
||||
});
|
||||
|
||||
test("a key sealed under one ID doesn't open as another's: a server "
|
||||
"can't swap stores' keys", () {
|
||||
expect(
|
||||
() => openDataKey(
|
||||
sodium,
|
||||
sealed,
|
||||
keyId: 'studyset-7',
|
||||
keys: account,
|
||||
),
|
||||
refusedFor(KeyRefusal.wrongDataKey),
|
||||
);
|
||||
});
|
||||
|
||||
test('an ID must be 1 to 255 bytes', () {
|
||||
expect(() => DataKey.generate(sodium, ''), throwsArgumentError);
|
||||
expect(
|
||||
() => DataKey.generate(sodium, 'x' * 256),
|
||||
throwsArgumentError,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group('content, sealed and signed', () {
|
||||
final author = AccountKeys.generate(sodium);
|
||||
final dataKey = DataKey.generate(sodium, 'agenda-2026');
|
||||
final context = utf8.encode('agenda_item/0192f3a4');
|
||||
final plainText = Uint8List.fromList(
|
||||
utf8.encode('{"title": "Study N3: 34 cards"}'),
|
||||
);
|
||||
final sealed = sealContent(
|
||||
sodium,
|
||||
plainText: plainText,
|
||||
dataKey: dataKey,
|
||||
author: author,
|
||||
context: context,
|
||||
);
|
||||
|
||||
Uint8List open(
|
||||
SealedContent what, {
|
||||
DataKey? withKey,
|
||||
Uint8List? signedBy,
|
||||
List<int>? at,
|
||||
}) => openContent(
|
||||
sodium,
|
||||
what,
|
||||
dataKey: withKey ?? dataKey,
|
||||
authorSigningPublicKey: signedBy ?? author.signingPublicKey,
|
||||
context: at ?? context,
|
||||
);
|
||||
|
||||
test("opens with the data key, its signature the author's", () {
|
||||
expect(open(sealed), plainText);
|
||||
expect(sealed.keyId, 'agenda-2026');
|
||||
expect(sealed.nonce, hasLength(24));
|
||||
expect(sealed.signature, hasLength(64));
|
||||
// The payload is no plain text.
|
||||
expect(
|
||||
utf8.decode(sealed.payload, allowMalformed: true),
|
||||
isNot(contains('Study')),
|
||||
);
|
||||
});
|
||||
|
||||
test('every sealing takes a new nonce', () {
|
||||
final again = sealContent(
|
||||
sodium,
|
||||
plainText: plainText,
|
||||
dataKey: dataKey,
|
||||
author: author,
|
||||
context: context,
|
||||
);
|
||||
expect(again.nonce, isNot(sealed.nonce));
|
||||
expect(again.payload, isNot(sealed.payload));
|
||||
});
|
||||
|
||||
test('another data key is refused, even under the same ID', () {
|
||||
expect(
|
||||
() => open(sealed, withKey: DataKey.generate(sodium, 'studyset-7')),
|
||||
refusedFor(KeyRefusal.wrongDataKey),
|
||||
);
|
||||
expect(
|
||||
() => open(sealed, withKey: DataKey.generate(sodium, 'agenda-2026')),
|
||||
refusedFor(KeyRefusal.wrongKeyOrTampered),
|
||||
);
|
||||
});
|
||||
|
||||
test('a payload, nonce, ID or signature changed is refused as forged', () {
|
||||
SealedContent changed({
|
||||
String? keyId,
|
||||
Uint8List? nonce,
|
||||
Uint8List? payload,
|
||||
Uint8List? signature,
|
||||
}) => SealedContent(
|
||||
keyId: keyId ?? sealed.keyId,
|
||||
nonce: nonce ?? sealed.nonce,
|
||||
payload: payload ?? sealed.payload,
|
||||
signature: signature ?? sealed.signature,
|
||||
);
|
||||
for (final tampered in [
|
||||
changed(payload: Uint8List.fromList(sealed.payload)..[0] ^= 1),
|
||||
changed(nonce: Uint8List.fromList(sealed.nonce)..[23] ^= 1),
|
||||
changed(signature: Uint8List.fromList(sealed.signature)..[10] ^= 1),
|
||||
changed(signature: sealed.signature.sublist(1)),
|
||||
]) {
|
||||
expect(() => open(tampered), refusedFor(KeyRefusal.forgedSignature));
|
||||
}
|
||||
// Another ID than the key's is caught before anything else.
|
||||
expect(
|
||||
() => open(changed(keyId: 'agenda-2027')),
|
||||
refusedFor(KeyRefusal.wrongDataKey),
|
||||
);
|
||||
});
|
||||
|
||||
test("someone else's signature, or content moved to another row, is "
|
||||
'refused', () {
|
||||
expect(
|
||||
() => open(
|
||||
sealed,
|
||||
signedBy: AccountKeys.generate(sodium).signingPublicKey,
|
||||
),
|
||||
refusedFor(KeyRefusal.forgedSignature),
|
||||
);
|
||||
expect(
|
||||
() => open(sealed, at: utf8.encode('agenda_item/0192f3a5')),
|
||||
refusedFor(KeyRefusal.forgedSignature),
|
||||
);
|
||||
});
|
||||
|
||||
test('content resealed by someone holding the data key but not the '
|
||||
"author's signing key doesn't pass as the author's", () {
|
||||
final forger = AccountKeys.generate(sodium);
|
||||
final forged = sealContent(
|
||||
sodium,
|
||||
plainText: Uint8List.fromList(utf8.encode('{"title": "forged"}')),
|
||||
dataKey: dataKey,
|
||||
author: forger,
|
||||
context: context,
|
||||
);
|
||||
expect(() => open(forged), refusedFor(KeyRefusal.forgedSignature));
|
||||
expect(open(forged, signedBy: forger.signingPublicKey), isNotEmpty);
|
||||
});
|
||||
});
|
||||
}
|
||||
138
packages/halkyon_keys/test/password_keys_test.dart
Normal file
138
packages/halkyon_keys/test/password_keys_test.dart
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
import 'dart:typed_data';
|
||||
|
||||
import 'package:halkyon_keys/halkyon_keys.dart';
|
||||
import 'package:sodium/sodium_sumo.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
Future<void> main() async {
|
||||
final sodium = await SodiumSumoInit.init();
|
||||
// Cheap costs for most tests; the production costs are checked once below.
|
||||
const cheap = PasswordKdf(opsLimit: 1, memLimit: 8192);
|
||||
final salt = Uint8List.fromList(List.generate(16, (i) => i));
|
||||
|
||||
PasswordKeys keysOf(String password, {Uint8List? withSalt}) =>
|
||||
derivePasswordKeys(
|
||||
sodium,
|
||||
password: password,
|
||||
salt: withSalt ?? salt,
|
||||
kdf: cheap,
|
||||
);
|
||||
|
||||
test('the same password and salt make the same keys, on any device', () {
|
||||
final first = keysOf('correct horse battery staple');
|
||||
final second = keysOf('correct horse battery staple');
|
||||
expect(first.srpPrivateValue, second.srpPrivateValue);
|
||||
expect(
|
||||
first.keyEncryptionKey.extractBytes(),
|
||||
second.keyEncryptionKey.extractBytes(),
|
||||
);
|
||||
});
|
||||
|
||||
test('another password, or another salt, makes other keys', () {
|
||||
final keys = keysOf('correct horse battery staple');
|
||||
final otherPassword = keysOf('correct horse battery stapler');
|
||||
final otherSalt = keysOf(
|
||||
'correct horse battery staple',
|
||||
withSalt: Uint8List.fromList(List.generate(16, (i) => i + 1)),
|
||||
);
|
||||
for (final other in [otherPassword, otherSalt]) {
|
||||
expect(other.srpPrivateValue, isNot(keys.srpPrivateValue));
|
||||
expect(
|
||||
other.keyEncryptionKey.extractBytes(),
|
||||
isNot(keys.keyEncryptionKey.extractBytes()),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("SRP's secret and the key-encryption key are unrelated halves", () {
|
||||
final keys = keysOf('a password');
|
||||
final srp = keys.srpSecret.extractBytes();
|
||||
expect(srp, hasLength(32));
|
||||
expect(keys.keyEncryptionKey.extractBytes(), hasLength(32));
|
||||
expect(keys.keyEncryptionKey.extractBytes(), isNot(srp));
|
||||
expect(keys.srpPrivateValue.bitLength, lessThanOrEqualTo(256));
|
||||
expect(keys.srpPrivateValue, greaterThan(BigInt.zero));
|
||||
});
|
||||
|
||||
test('a salt of another length is refused', () {
|
||||
expect(
|
||||
() => derivePasswordKeys(
|
||||
sodium,
|
||||
password: 'a password',
|
||||
salt: Uint8List(15),
|
||||
kdf: cheap,
|
||||
),
|
||||
throwsArgumentError,
|
||||
);
|
||||
});
|
||||
|
||||
test('new salts are 16 random bytes', () {
|
||||
final first = newPasswordSalt(sodium);
|
||||
expect(first, hasLength(16));
|
||||
expect(newPasswordSalt(sodium), isNot(first));
|
||||
});
|
||||
|
||||
test('new passwords cost 64 MiB and 3 passes, and that works', () {
|
||||
expect(PasswordKdf.current.memLimit, 64 * 1024 * 1024);
|
||||
expect(PasswordKdf.current.opsLimit, 3);
|
||||
// The floor is apart from what new passwords take, so raising the
|
||||
// latter never locks out an account made before.
|
||||
expect(PasswordKdf.minimum.memLimit, 64 * 1024 * 1024);
|
||||
expect(PasswordKdf.minimum.opsLimit, 3);
|
||||
expect(
|
||||
PasswordKdf.current.memLimit,
|
||||
greaterThanOrEqualTo(PasswordKdf.minimum.memLimit),
|
||||
);
|
||||
expect(
|
||||
PasswordKdf.current.opsLimit,
|
||||
greaterThanOrEqualTo(PasswordKdf.minimum.opsLimit),
|
||||
);
|
||||
final keys = derivePasswordKeys(
|
||||
sodium,
|
||||
password: 'a password',
|
||||
salt: salt,
|
||||
);
|
||||
expect(keys.srpPrivateValue, greaterThan(BigInt.zero));
|
||||
keys.dispose();
|
||||
});
|
||||
|
||||
group('the costs kept with an account', () {
|
||||
test('the floor itself is read', () {
|
||||
final read = PasswordKdf.fromJson(PasswordKdf.minimum.toJson());
|
||||
expect(read.opsLimit, PasswordKdf.minimum.opsLimit);
|
||||
expect(read.memLimit, PasswordKdf.minimum.memLimit);
|
||||
});
|
||||
|
||||
test('round-trip', () {
|
||||
const raised = PasswordKdf(opsLimit: 4, memLimit: 128 * 1024 * 1024);
|
||||
final json = raised.toJson();
|
||||
expect(json['algorithm'], 'argon2id13');
|
||||
final read = PasswordKdf.fromJson(json);
|
||||
expect(read.opsLimit, 4);
|
||||
expect(read.memLimit, 128 * 1024 * 1024);
|
||||
});
|
||||
|
||||
test('below the floor, or of another algorithm, are refused: a register '
|
||||
"can't make guessing cheaper", () {
|
||||
for (final json in <Map<String, Object?>>[
|
||||
{'algorithm': 'argon2id13', 'opsLimit': 2, 'memLimit': 64 << 20},
|
||||
{'algorithm': 'argon2id13', 'opsLimit': 3, 'memLimit': 32 << 20},
|
||||
{'algorithm': 'argon2i13', 'opsLimit': 3, 'memLimit': 64 << 20},
|
||||
{'algorithm': 'argon2id13', 'opsLimit': '3', 'memLimit': 64 << 20},
|
||||
{},
|
||||
]) {
|
||||
expect(
|
||||
() => PasswordKdf.fromJson(json),
|
||||
throwsA(
|
||||
isA<KeyRefused>().having(
|
||||
(refused) => refused.reason,
|
||||
'reason',
|
||||
KeyRefusal.weakPasswordKdf,
|
||||
),
|
||||
),
|
||||
reason: '$json',
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
132
packages/halkyon_keys/test/recovery_phrase_test.dart
Normal file
132
packages/halkyon_keys/test/recovery_phrase_test.dart
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
import 'dart:typed_data';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:halkyon_keys/halkyon_keys.dart';
|
||||
import 'package:halkyon_keys/src/bip39_english.dart';
|
||||
import 'package:sodium/sodium_sumo.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
import 'bip39_vectors.dart';
|
||||
|
||||
/// [hex] as bytes.
|
||||
Uint8List _bytes(String hex) => Uint8List.fromList([
|
||||
for (var i = 0; i < hex.length; i += 2)
|
||||
int.parse(hex.substring(i, i + 2), radix: 16),
|
||||
]);
|
||||
|
||||
Future<void> main() async {
|
||||
final sodium = await SodiumSumoInit.init();
|
||||
|
||||
Matcher refusedFor(KeyRefusal reason) => throwsA(
|
||||
isA<KeyRefused>().having((refused) => refused.reason, 'reason', reason),
|
||||
);
|
||||
|
||||
test("the word list is BIP-39's English list: 2,048 words, sorted, each "
|
||||
'once', () {
|
||||
expect(bip39English, hasLength(2048));
|
||||
expect(bip39English.toSet(), hasLength(2048));
|
||||
expect([...bip39English]..sort(), bip39English);
|
||||
// The SHA-256 of english.txt, a word a line.
|
||||
expect(
|
||||
sha256.convert('${bip39English.join('\n')}\n'.codeUnits).toString(),
|
||||
'2f5eed53a4727b4bf8880d8f3f199efc90e58503646d9ff8eff3a2ed3b24dbda',
|
||||
);
|
||||
});
|
||||
|
||||
group("BIP-39's English test vectors (trezor/python-mnemonic)", () {
|
||||
for (final (entropy, mnemonic) in bip39Vectors) {
|
||||
test(mnemonic.split(' ').take(3).join(' '), () {
|
||||
expect(recoveryPhraseOf(_bytes(entropy)), mnemonic);
|
||||
expect(entropyOfRecoveryPhrase(mnemonic), _bytes(entropy));
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('a new phrase is 24 words, never the same twice, and stands for '
|
||||
'256 bits', () {
|
||||
final phrase = newRecoveryPhrase(sodium);
|
||||
expect(phrase.split(' '), hasLength(24));
|
||||
expect(newRecoveryPhrase(sodium), isNot(phrase));
|
||||
expect(entropyOfRecoveryPhrase(phrase), hasLength(recoveryEntropyBytes));
|
||||
});
|
||||
|
||||
test('case and the spaces between words make no difference', () {
|
||||
final phrase = newRecoveryPhrase(sodium);
|
||||
final typed = ' ${phrase.toUpperCase().replaceAll(' ', '\n ')} ';
|
||||
expect(entropyOfRecoveryPhrase(typed), entropyOfRecoveryPhrase(phrase));
|
||||
});
|
||||
|
||||
group('refused', () {
|
||||
final phrase = newRecoveryPhrase(sodium);
|
||||
final words = phrase.split(' ');
|
||||
|
||||
test('a phrase of another length', () {
|
||||
for (final count in [0, 11, 13, 23, 25]) {
|
||||
final shorter = [
|
||||
for (var i = 0; i < count; i++) words[i % words.length],
|
||||
].join(' ');
|
||||
expect(
|
||||
() => entropyOfRecoveryPhrase(shorter),
|
||||
refusedFor(KeyRefusal.phraseLength),
|
||||
reason: '$count words',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('a word not on the list', () {
|
||||
expect(
|
||||
() => entropyOfRecoveryPhrase([...words.take(23), 'zzzz'].join(' ')),
|
||||
refusedFor(KeyRefusal.phraseWord),
|
||||
);
|
||||
});
|
||||
|
||||
test('a checksum that fails: a word changed, or two swapped', () {
|
||||
// A fixed vector, so the changes are known to fail (a random phrase
|
||||
// changed passes the 8-bit checksum once in 256).
|
||||
final fixed = bip39Vectors
|
||||
.firstWhere((vector) => vector.$2.startsWith('letter advice cage'))
|
||||
.$2
|
||||
.split(' ');
|
||||
final changed = [...fixed]..[0] = 'ability';
|
||||
final swapped = [...fixed]
|
||||
..[0] = fixed[1]
|
||||
..[1] = fixed[0];
|
||||
for (final wrong in [changed, swapped]) {
|
||||
expect(
|
||||
() => entropyOfRecoveryPhrase(wrong.join(' ')),
|
||||
refusedFor(KeyRefusal.phraseChecksum),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test(
|
||||
"a 12-word BIP-39 phrase is no recovery phrase: it hasn't 256 bits",
|
||||
() {
|
||||
expect(
|
||||
() => recoveryKeyOf(sodium, bip39Vectors.first.$2),
|
||||
refusedFor(KeyRefusal.phraseLength),
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('the recovery key is the same from the same phrase, another from '
|
||||
'another', () {
|
||||
final phrase = newRecoveryPhrase(sodium);
|
||||
final key = recoveryKeyOf(sodium, phrase).extractBytes();
|
||||
expect(key, hasLength(32));
|
||||
expect(recoveryKeyOf(sodium, phrase.toUpperCase()).extractBytes(), key);
|
||||
expect(
|
||||
recoveryKeyOf(sodium, newRecoveryPhrase(sodium)).extractBytes(),
|
||||
isNot(key),
|
||||
);
|
||||
// The key isn't the phrase's bits themselves.
|
||||
expect(key, isNot(entropyOfRecoveryPhrase(phrase)));
|
||||
});
|
||||
|
||||
test('entropy of a length BIP-39 has no phrase for is refused', () {
|
||||
for (final length in [0, 15, 17, 33]) {
|
||||
expect(() => recoveryPhraseOf(Uint8List(length)), throwsArgumentError);
|
||||
}
|
||||
});
|
||||
}
|
||||
Loading…
Reference in a new issue