initial commit
Some checks failed
CI / lint (push) Successful in 1m37s
CI / test-python (push) Successful in 1m49s
CI / test-zig (push) Successful in 1m39s
CI / test-wasm (push) Successful in 1m54s
CI / test (push) Successful in 14m44s
CI / miri (push) Successful in 14m18s
CI / build (push) Successful in 1m9s
CI / fuzz-regression (push) Successful in 9m9s
CI / publish (push) Failing after 1m10s
CI / publish-python (push) Failing after 1m46s
CI / publish-wasm (push) Has been cancelled
Some checks failed
CI / lint (push) Successful in 1m37s
CI / test-python (push) Successful in 1m49s
CI / test-zig (push) Successful in 1m39s
CI / test-wasm (push) Successful in 1m54s
CI / test (push) Successful in 14m44s
CI / miri (push) Successful in 14m18s
CI / build (push) Successful in 1m9s
CI / fuzz-regression (push) Successful in 9m9s
CI / publish (push) Failing after 1m10s
CI / publish-python (push) Failing after 1m46s
CI / publish-wasm (push) Has been cancelled
Signed-off-by: Kamal Tufekcic <kamal@lo.sh>
This commit is contained in:
commit
1d99048c95
165830 changed files with 79062 additions and 0 deletions
22
soliton_py/Cargo.toml
Normal file
22
soliton_py/Cargo.toml
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
[package]
|
||||
name = "soliton-python"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
homepage.workspace = true
|
||||
authors.workspace = true
|
||||
description = "Python bindings for libsoliton — post-quantum cryptographic library"
|
||||
categories = ["cryptography", "api-bindings"]
|
||||
keywords = ["post-quantum", "soliton", "python", "pyo3"]
|
||||
# Not published to crates.io — distributed via PyPI as a maturin wheel.
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
name = "soliton"
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
libsoliton = { workspace = true }
|
||||
pyo3 = { version = "0.28", features = ["extension-module"] }
|
||||
zeroize = { workspace = true }
|
||||
661
soliton_py/LICENSE.md
Normal file
661
soliton_py/LICENSE.md
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/>.
|
||||
168
soliton_py/README.md
Normal file
168
soliton_py/README.md
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
# soliton
|
||||
|
||||
Python bindings for [libsoliton](https://git.lo.sh/lo/libsoliton) — a pure-Rust post-quantum cryptographic library providing composite identity keys (X-Wing + ML-DSA-65), hybrid signatures, KEM-based authentication, asynchronous key exchange, double-ratchet message encryption, streaming AEAD, and encrypted storage.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
pip install soliton
|
||||
```
|
||||
|
||||
Builds from source via [maturin](https://www.maturin.rs/) — requires a Rust toolchain.
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Identity Keys
|
||||
|
||||
```python
|
||||
import soliton
|
||||
|
||||
# Generate a post-quantum identity keypair.
|
||||
with soliton.Identity.generate() as alice:
|
||||
# Sign a message (Ed25519 + ML-DSA-65 hybrid).
|
||||
sig = alice.sign(b"hello")
|
||||
alice.verify(b"hello", sig)
|
||||
|
||||
# Fingerprint (SHA3-256 of public key).
|
||||
print(alice.fingerprint_hex())
|
||||
|
||||
# Persist keys.
|
||||
pk = alice.public_key() # 3200 bytes
|
||||
sk = alice.secret_key() # 2496 bytes
|
||||
# Secret key is zeroized on context exit.
|
||||
```
|
||||
|
||||
### Key Exchange (KEX)
|
||||
|
||||
```python
|
||||
# Bob generates a signed pre-key.
|
||||
spk_pub, spk_sk = soliton.xwing_keygen()
|
||||
spk_sig = soliton.kex_sign_prekey(bob_sk, spk_pub)
|
||||
|
||||
# Alice initiates a session.
|
||||
initiated = soliton.kex_initiate(
|
||||
alice_pk, alice_sk, bob_pk,
|
||||
spk_pub, spk_id=1, spk_sig=spk_sig,
|
||||
crypto_version="lo-crypto-v1",
|
||||
)
|
||||
|
||||
# Bob receives the session.
|
||||
received = soliton.kex_receive(
|
||||
bob_pk, bob_sk, alice_pk,
|
||||
initiated.session_init_encoded(),
|
||||
initiated.sender_sig(), spk_sk,
|
||||
)
|
||||
```
|
||||
|
||||
### Ratchet (Ongoing Messaging)
|
||||
|
||||
```python
|
||||
# First message (pre-ratchet).
|
||||
aad = soliton.kex_build_first_message_aad(
|
||||
initiated.sender_fingerprint(),
|
||||
initiated.recipient_fingerprint(),
|
||||
initiated.session_init_encoded(),
|
||||
)
|
||||
ct, rik_a = soliton.Ratchet.encrypt_first_message(
|
||||
initiated.take_initial_chain_key(), b"hello bob", aad,
|
||||
)
|
||||
pt, rik_b = soliton.Ratchet.decrypt_first_message(
|
||||
received.take_initial_chain_key(), ct, aad,
|
||||
)
|
||||
|
||||
# Initialize ratchets.
|
||||
with soliton.Ratchet.init_alice(
|
||||
initiated.take_root_key(), rik_a,
|
||||
alice_fp, bob_fp, initiated.ek_pk(), initiated.ek_sk(),
|
||||
) as alice_r:
|
||||
header, ciphertext = alice_r.encrypt(b"message 1")
|
||||
|
||||
# Serialize for persistence.
|
||||
blob, epoch = alice_r.to_bytes() # consumes the ratchet
|
||||
```
|
||||
|
||||
### Encrypted Storage
|
||||
|
||||
```python
|
||||
with soliton.StorageKeyRing(version=1, key=key_bytes) as ring:
|
||||
blob = ring.encrypt_blob("channel-1", "segment-0", plaintext)
|
||||
data = ring.decrypt_blob("channel-1", "segment-0", blob)
|
||||
|
||||
# Key rotation.
|
||||
ring.add_key(version=2, key=new_key, make_active=True)
|
||||
```
|
||||
|
||||
### Streaming AEAD (File Encryption)
|
||||
|
||||
```python
|
||||
with soliton.StreamEncryptor(key) as enc:
|
||||
header = enc.header() # 26 bytes — send first
|
||||
ct1 = enc.encrypt_chunk(chunk1) # non-final: must be 1 MiB
|
||||
ct2 = enc.encrypt_chunk(chunk2, is_last=True) # final: any size
|
||||
|
||||
with soliton.StreamDecryptor(key, header) as dec:
|
||||
pt1, is_last = dec.decrypt_chunk(ct1)
|
||||
pt2, is_last = dec.decrypt_chunk(ct2)
|
||||
```
|
||||
|
||||
### Authentication (Zero-Knowledge)
|
||||
|
||||
```python
|
||||
# Server generates challenge.
|
||||
ct, token = soliton.auth_challenge(client_pk)
|
||||
|
||||
# Client responds.
|
||||
proof = soliton.auth_respond(client_sk, ct)
|
||||
|
||||
# Server verifies (constant-time).
|
||||
assert soliton.auth_verify(token, proof)
|
||||
```
|
||||
|
||||
### Primitives
|
||||
|
||||
```python
|
||||
digest = soliton.sha3_256(b"data") # 32 bytes
|
||||
tag = soliton.hmac_sha3_256(key, data) # 32 bytes
|
||||
okm = soliton.hkdf_sha3_256(salt, ikm, info, length=64) # variable
|
||||
ok = soliton.hmac_sha3_256_verify(tag1, tag2) # constant-time
|
||||
phrase = soliton.verification_phrase(pk_a, pk_b) # 6 EFF words
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
All errors are subclasses of `soliton.SolitonError`:
|
||||
|
||||
| Exception | Meaning |
|
||||
|-----------|---------|
|
||||
| `AeadError` | AEAD decryption failed (wrong key, tampered ciphertext) |
|
||||
| `VerificationError` | Signature verification failed |
|
||||
| `BundleVerificationError` | Pre-key bundle invalid |
|
||||
| `DuplicateMessageError` | Replayed message counter |
|
||||
| `ChainExhaustedError` | Counter-space exhausted — re-establish session |
|
||||
| `InvalidLengthError` | Wrong-size parameter |
|
||||
| `InvalidDataError` | Malformed input |
|
||||
|
||||
## Context Managers
|
||||
|
||||
All types holding secret material support `with` statements for automatic zeroization:
|
||||
|
||||
```python
|
||||
with soliton.Identity.generate() as id:
|
||||
... # secret key zeroized on exit
|
||||
|
||||
with soliton.Ratchet.init_alice(...) as r:
|
||||
... # ratchet state reset on exit
|
||||
|
||||
with soliton.StorageKeyRing(1, key) as ring:
|
||||
... # key material zeroized on exit
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
- [Specification.md](https://git.lo.sh/lo/libsoliton/src/branch/main/Specification.md) — full cryptographic specification
|
||||
- [CHEATSHEET.md](https://git.lo.sh/lo/libsoliton/src/branch/main/CHEATSHEET.md) — API quick reference
|
||||
- [Abstract.md](https://git.lo.sh/lo/libsoliton/src/branch/main/Abstract.md) — formal security model
|
||||
|
||||
## License
|
||||
|
||||
[AGPL-3.0-only](LICENSE.md)
|
||||
43
soliton_py/pyproject.toml
Normal file
43
soliton_py/pyproject.toml
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
[build-system]
|
||||
requires = ["maturin>=1.7,<2.0"]
|
||||
build-backend = "maturin"
|
||||
|
||||
[project]
|
||||
name = "soliton"
|
||||
version = "0.1.0"
|
||||
description = "Python bindings for libsoliton — post-quantum cryptographic library"
|
||||
license = { text = "AGPL-3.0-only" }
|
||||
requires-python = ">=3.10"
|
||||
readme = "README.md"
|
||||
authors = [{ name = "LO Contributors" }]
|
||||
keywords = ["post-quantum", "cryptography", "x-wing", "double-ratchet", "e2ee"]
|
||||
classifiers = [
|
||||
"Development Status :: 3 - Alpha",
|
||||
"Intended Audience :: Developers",
|
||||
"License :: OSI Approved :: GNU Affero General Public License v3",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Programming Language :: Python :: 3.13",
|
||||
"Programming Language :: Python :: 3.14",
|
||||
"Programming Language :: Python :: Implementation :: CPython",
|
||||
"Programming Language :: Rust",
|
||||
"Topic :: Security :: Cryptography",
|
||||
"Typing :: Typed",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Repository = "https://git.lo.sh/lo/libsoliton"
|
||||
Documentation = "https://docs.rs/libsoliton"
|
||||
|
||||
[project.optional-dependencies]
|
||||
test = ["pytest>=8.0"]
|
||||
|
||||
[tool.maturin]
|
||||
features = ["pyo3/extension-module"]
|
||||
module-name = "soliton._native"
|
||||
python-source = "python"
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
142
soliton_py/python/soliton/__init__.py
Normal file
142
soliton_py/python/soliton/__init__.py
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
"""libsoliton — post-quantum cryptographic library.
|
||||
|
||||
Pure-Rust post-quantum cryptographic library providing composite identity keys
|
||||
(X-Wing + ML-DSA-65), hybrid signatures, KEM-based authentication, asynchronous
|
||||
key exchange, double-ratchet message encryption, and encrypted storage.
|
||||
|
||||
Usage::
|
||||
|
||||
import soliton
|
||||
|
||||
# Identity
|
||||
with soliton.Identity.generate() as alice:
|
||||
sig = alice.sign(b"hello")
|
||||
alice.verify(b"hello", sig)
|
||||
|
||||
# KEX (key exchange)
|
||||
initiated = soliton.kex_initiate(alice_pk, alice_sk, bob_pk, spk_pub, ...)
|
||||
received = soliton.kex_receive(bob_pk, bob_sk, alice_pk, si_encoded, ...)
|
||||
|
||||
# Ratchet (ongoing messaging)
|
||||
with soliton.Ratchet.init_alice(root_key, chain_key, ...) as r:
|
||||
header, ct = r.encrypt(b"hello")
|
||||
|
||||
# Streaming AEAD (file encryption)
|
||||
with soliton.StreamEncryptor(key) as enc:
|
||||
header = enc.header()
|
||||
chunk = enc.encrypt_chunk(data, is_last=True)
|
||||
|
||||
# Storage
|
||||
with soliton.StorageKeyRing(1, key) as ring:
|
||||
blob = ring.encrypt_blob("ch", "seg", plaintext)
|
||||
|
||||
# Auth
|
||||
ct, token = soliton.auth_challenge(client_pk)
|
||||
proof = soliton.auth_respond(client_sk, ct)
|
||||
ok = soliton.auth_verify(token, proof)
|
||||
"""
|
||||
|
||||
from soliton._native import (
|
||||
# Version
|
||||
__version__,
|
||||
VERSION,
|
||||
# Errors
|
||||
SolitonError,
|
||||
InvalidLengthError,
|
||||
InvalidDataError,
|
||||
AeadError,
|
||||
VerificationError,
|
||||
BundleVerificationError,
|
||||
DecapsulationError,
|
||||
DuplicateMessageError,
|
||||
ChainExhaustedError,
|
||||
UnsupportedVersionError,
|
||||
UnsupportedCryptoVersionError,
|
||||
InternalError,
|
||||
# Identity
|
||||
Identity,
|
||||
# Primitives
|
||||
sha3_256,
|
||||
fingerprint_hex,
|
||||
hmac_sha3_256,
|
||||
hmac_sha3_256_verify,
|
||||
hkdf_sha3_256,
|
||||
xwing_keygen,
|
||||
# Auth
|
||||
auth_challenge,
|
||||
auth_respond,
|
||||
auth_verify,
|
||||
# Verification
|
||||
verification_phrase,
|
||||
# KEX
|
||||
InitiatedSession,
|
||||
ReceivedSession,
|
||||
kex_sign_prekey,
|
||||
kex_verify_bundle,
|
||||
kex_initiate,
|
||||
kex_receive,
|
||||
kex_encode_session_init,
|
||||
kex_decode_session_init,
|
||||
kex_build_first_message_aad,
|
||||
# Ratchet
|
||||
Ratchet,
|
||||
# Storage
|
||||
StorageKeyRing,
|
||||
# Streaming
|
||||
StreamEncryptor,
|
||||
StreamDecryptor,
|
||||
# Call Keys
|
||||
CallKeys,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"__version__",
|
||||
"VERSION",
|
||||
# Errors
|
||||
"SolitonError",
|
||||
"InvalidLengthError",
|
||||
"InvalidDataError",
|
||||
"AeadError",
|
||||
"VerificationError",
|
||||
"BundleVerificationError",
|
||||
"DecapsulationError",
|
||||
"DuplicateMessageError",
|
||||
"ChainExhaustedError",
|
||||
"UnsupportedVersionError",
|
||||
"UnsupportedCryptoVersionError",
|
||||
"InternalError",
|
||||
# Identity
|
||||
"Identity",
|
||||
# Primitives
|
||||
"sha3_256",
|
||||
"fingerprint_hex",
|
||||
"hmac_sha3_256",
|
||||
"hmac_sha3_256_verify",
|
||||
"hkdf_sha3_256",
|
||||
"xwing_keygen",
|
||||
# Auth
|
||||
"auth_challenge",
|
||||
"auth_respond",
|
||||
"auth_verify",
|
||||
# Verification
|
||||
"verification_phrase",
|
||||
# KEX
|
||||
"InitiatedSession",
|
||||
"ReceivedSession",
|
||||
"kex_sign_prekey",
|
||||
"kex_verify_bundle",
|
||||
"kex_initiate",
|
||||
"kex_receive",
|
||||
"kex_encode_session_init",
|
||||
"kex_decode_session_init",
|
||||
"kex_build_first_message_aad",
|
||||
# Ratchet
|
||||
"Ratchet",
|
||||
# Storage
|
||||
"StorageKeyRing",
|
||||
# Streaming
|
||||
"StreamEncryptor",
|
||||
"StreamDecryptor",
|
||||
# Call Keys
|
||||
"CallKeys",
|
||||
]
|
||||
57
soliton_py/src/auth.rs
Normal file
57
soliton_py/src/auth.rs
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
//! LO-Auth: zero-knowledge authentication via KEM challenge-response.
|
||||
|
||||
use pyo3::prelude::*;
|
||||
use pyo3::types::PyBytes;
|
||||
|
||||
use crate::errors::to_py_err;
|
||||
|
||||
/// Generate an authentication challenge (server-side).
|
||||
///
|
||||
/// Returns (ciphertext, expected_token) as a tuple of bytes.
|
||||
#[pyfunction]
|
||||
fn auth_challenge<'py>(py: Python<'py>, client_pk: &[u8]) -> PyResult<(Py<PyBytes>, Py<PyBytes>)> {
|
||||
let pk =
|
||||
soliton::identity::IdentityPublicKey::from_bytes(client_pk.to_vec()).map_err(to_py_err)?;
|
||||
let (ct, token) = soliton::auth::auth_challenge(&pk).map_err(to_py_err)?;
|
||||
Ok((
|
||||
PyBytes::new(py, ct.as_bytes()).into(),
|
||||
PyBytes::new(py, &*token).into(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Respond to an authentication challenge (client-side).
|
||||
///
|
||||
/// Returns the 32-byte proof.
|
||||
#[pyfunction]
|
||||
fn auth_respond<'py>(
|
||||
py: Python<'py>,
|
||||
client_sk: &[u8],
|
||||
ciphertext: &[u8],
|
||||
) -> PyResult<Py<PyBytes>> {
|
||||
let sk =
|
||||
soliton::identity::IdentitySecretKey::from_bytes(client_sk.to_vec()).map_err(to_py_err)?;
|
||||
let ct = soliton::primitives::xwing::Ciphertext::from_bytes(ciphertext.to_vec())
|
||||
.map_err(to_py_err)?;
|
||||
let proof = soliton::auth::auth_respond(&sk, &ct).map_err(to_py_err)?;
|
||||
Ok(PyBytes::new(py, &*proof).into())
|
||||
}
|
||||
|
||||
/// Verify an authentication proof (server-side). Constant-time.
|
||||
#[pyfunction]
|
||||
fn auth_verify(expected_token: &[u8], proof: &[u8]) -> PyResult<bool> {
|
||||
if expected_token.len() != 32 || proof.len() != 32 {
|
||||
return Err(crate::errors::InvalidLengthError::new_err(
|
||||
"both inputs must be 32 bytes",
|
||||
));
|
||||
}
|
||||
let a: &[u8; 32] = expected_token.try_into().unwrap();
|
||||
let b: &[u8; 32] = proof.try_into().unwrap();
|
||||
Ok(soliton::auth::auth_verify(a, b))
|
||||
}
|
||||
|
||||
pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add_function(wrap_pyfunction!(auth_challenge, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(auth_respond, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(auth_verify, m)?)?;
|
||||
Ok(())
|
||||
}
|
||||
84
soliton_py/src/call.rs
Normal file
84
soliton_py/src/call.rs
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
//! Call key derivation for encrypted voice/video.
|
||||
|
||||
use pyo3::prelude::*;
|
||||
use pyo3::types::PyBytes;
|
||||
|
||||
use crate::errors::to_py_err;
|
||||
|
||||
/// Call keys for encrypted voice/video media.
|
||||
///
|
||||
/// Derived from a ratchet session's root key and an ephemeral KEM shared secret.
|
||||
/// Keys are role-assigned by fingerprint order — both parties get the same
|
||||
/// send/recv assignment without coordination.
|
||||
///
|
||||
/// Use as a context manager for automatic zeroization::
|
||||
///
|
||||
/// with ratchet.derive_call_keys(kem_ss, call_id) as keys:
|
||||
/// send = keys.send_key()
|
||||
/// recv = keys.recv_key()
|
||||
/// keys.advance() # derive next round
|
||||
#[pyclass]
|
||||
pub struct CallKeys {
|
||||
inner: Option<soliton::call::CallKeys>,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl CallKeys {
|
||||
/// Current send key (32 bytes).
|
||||
fn send_key<'py>(&self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
|
||||
let inner = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("call keys consumed"))?;
|
||||
Ok(PyBytes::new(py, inner.send_key()).into())
|
||||
}
|
||||
|
||||
/// Current recv key (32 bytes).
|
||||
fn recv_key<'py>(&self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
|
||||
let inner = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("call keys consumed"))?;
|
||||
Ok(PyBytes::new(py, inner.recv_key()).into())
|
||||
}
|
||||
|
||||
/// Advance the call chain — derives fresh keys, zeroizes old ones.
|
||||
///
|
||||
/// Raises ``ChainExhaustedError`` after 2^24 advances.
|
||||
fn advance(&mut self) -> PyResult<()> {
|
||||
let inner = self
|
||||
.inner
|
||||
.as_mut()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("call keys consumed"))?;
|
||||
inner.advance().map_err(to_py_err)
|
||||
}
|
||||
|
||||
/// Zeroize all key material.
|
||||
fn close(&mut self) {
|
||||
self.inner = None;
|
||||
}
|
||||
|
||||
fn __enter__(slf: Py<Self>) -> Py<Self> {
|
||||
slf
|
||||
}
|
||||
|
||||
fn __exit__(
|
||||
&mut self,
|
||||
_exc_type: Option<&Bound<'_, PyAny>>,
|
||||
_exc_val: Option<&Bound<'_, PyAny>>,
|
||||
_exc_tb: Option<&Bound<'_, PyAny>>,
|
||||
) {
|
||||
self.close();
|
||||
}
|
||||
}
|
||||
|
||||
impl CallKeys {
|
||||
pub fn from_inner(inner: soliton::call::CallKeys) -> Self {
|
||||
Self { inner: Some(inner) }
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add_class::<CallKeys>()?;
|
||||
Ok(())
|
||||
}
|
||||
131
soliton_py/src/errors.rs
Normal file
131
soliton_py/src/errors.rs
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
//! Error type mapping from soliton::error::Error to Python exceptions.
|
||||
|
||||
use pyo3::create_exception;
|
||||
use pyo3::exceptions::PyException;
|
||||
use pyo3::prelude::*;
|
||||
|
||||
// Each soliton error variant gets a dedicated Python exception class,
|
||||
// all inheriting from SolitonError.
|
||||
create_exception!(
|
||||
soliton,
|
||||
SolitonError,
|
||||
PyException,
|
||||
"Base exception for all soliton errors."
|
||||
);
|
||||
create_exception!(
|
||||
soliton,
|
||||
InvalidLengthError,
|
||||
SolitonError,
|
||||
"Wrong-size parameter."
|
||||
);
|
||||
create_exception!(
|
||||
soliton,
|
||||
InvalidDataError,
|
||||
SolitonError,
|
||||
"Structurally invalid content."
|
||||
);
|
||||
create_exception!(soliton, AeadError, SolitonError, "AEAD decryption failed.");
|
||||
create_exception!(
|
||||
soliton,
|
||||
VerificationError,
|
||||
SolitonError,
|
||||
"Signature verification failed."
|
||||
);
|
||||
create_exception!(
|
||||
soliton,
|
||||
BundleVerificationError,
|
||||
SolitonError,
|
||||
"Pre-key bundle verification failed."
|
||||
);
|
||||
create_exception!(
|
||||
soliton,
|
||||
DecapsulationError,
|
||||
SolitonError,
|
||||
"KEM decapsulation failed."
|
||||
);
|
||||
create_exception!(
|
||||
soliton,
|
||||
DuplicateMessageError,
|
||||
SolitonError,
|
||||
"Replayed or already-seen message."
|
||||
);
|
||||
create_exception!(
|
||||
soliton,
|
||||
ChainExhaustedError,
|
||||
SolitonError,
|
||||
"Counter-space exhausted."
|
||||
);
|
||||
create_exception!(
|
||||
soliton,
|
||||
UnsupportedVersionError,
|
||||
SolitonError,
|
||||
"Unsupported blob version."
|
||||
);
|
||||
create_exception!(
|
||||
soliton,
|
||||
UnsupportedCryptoVersionError,
|
||||
SolitonError,
|
||||
"Unrecognized crypto version."
|
||||
);
|
||||
create_exception!(
|
||||
soliton,
|
||||
InternalError,
|
||||
SolitonError,
|
||||
"Internal invariant violated."
|
||||
);
|
||||
|
||||
/// Convert a soliton::error::Error into the appropriate Python exception.
|
||||
pub fn to_py_err(e: soliton::error::Error) -> PyErr {
|
||||
use soliton::error::Error;
|
||||
match e {
|
||||
Error::InvalidLength { .. } => InvalidLengthError::new_err(e.to_string()),
|
||||
Error::InvalidData => InvalidDataError::new_err(e.to_string()),
|
||||
Error::AeadFailed => AeadError::new_err(e.to_string()),
|
||||
Error::VerificationFailed => VerificationError::new_err(e.to_string()),
|
||||
Error::BundleVerificationFailed => BundleVerificationError::new_err(e.to_string()),
|
||||
Error::DecapsulationFailed => DecapsulationError::new_err(e.to_string()),
|
||||
Error::DuplicateMessage => DuplicateMessageError::new_err(e.to_string()),
|
||||
Error::ChainExhausted => ChainExhaustedError::new_err(e.to_string()),
|
||||
Error::UnsupportedVersion => UnsupportedVersionError::new_err(e.to_string()),
|
||||
Error::UnsupportedCryptoVersion => UnsupportedCryptoVersionError::new_err(e.to_string()),
|
||||
Error::Internal => InternalError::new_err(e.to_string()),
|
||||
_ => SolitonError::new_err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add("SolitonError", m.py().get_type::<SolitonError>())?;
|
||||
m.add(
|
||||
"InvalidLengthError",
|
||||
m.py().get_type::<InvalidLengthError>(),
|
||||
)?;
|
||||
m.add("InvalidDataError", m.py().get_type::<InvalidDataError>())?;
|
||||
m.add("AeadError", m.py().get_type::<AeadError>())?;
|
||||
m.add("VerificationError", m.py().get_type::<VerificationError>())?;
|
||||
m.add(
|
||||
"BundleVerificationError",
|
||||
m.py().get_type::<BundleVerificationError>(),
|
||||
)?;
|
||||
m.add(
|
||||
"DecapsulationError",
|
||||
m.py().get_type::<DecapsulationError>(),
|
||||
)?;
|
||||
m.add(
|
||||
"DuplicateMessageError",
|
||||
m.py().get_type::<DuplicateMessageError>(),
|
||||
)?;
|
||||
m.add(
|
||||
"ChainExhaustedError",
|
||||
m.py().get_type::<ChainExhaustedError>(),
|
||||
)?;
|
||||
m.add(
|
||||
"UnsupportedVersionError",
|
||||
m.py().get_type::<UnsupportedVersionError>(),
|
||||
)?;
|
||||
m.add(
|
||||
"UnsupportedCryptoVersionError",
|
||||
m.py().get_type::<UnsupportedCryptoVersionError>(),
|
||||
)?;
|
||||
m.add("InternalError", m.py().get_type::<InternalError>())?;
|
||||
Ok(())
|
||||
}
|
||||
112
soliton_py/src/identity.rs
Normal file
112
soliton_py/src/identity.rs
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
//! Identity key management: keygen, sign, verify, fingerprint.
|
||||
|
||||
use crate::errors::to_py_err;
|
||||
use pyo3::prelude::*;
|
||||
use pyo3::types::PyBytes;
|
||||
|
||||
/// An identity keypair (X-Wing + Ed25519 + ML-DSA-65).
|
||||
///
|
||||
/// Secret key material is zeroized when this object is garbage collected.
|
||||
/// For deterministic cleanup, call `close()` explicitly or use as a context
|
||||
/// manager: `with Identity.generate() as id: ...`
|
||||
#[pyclass]
|
||||
pub struct Identity {
|
||||
pk: soliton::identity::IdentityPublicKey,
|
||||
sk: Option<soliton::identity::IdentitySecretKey>,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl Identity {
|
||||
/// Generate a fresh identity keypair.
|
||||
#[staticmethod]
|
||||
fn generate() -> PyResult<Self> {
|
||||
let id = soliton::identity::generate_identity().map_err(to_py_err)?;
|
||||
Ok(Self {
|
||||
pk: id.public_key,
|
||||
sk: Some(id.secret_key),
|
||||
})
|
||||
}
|
||||
|
||||
/// Reconstruct from serialized public + secret key bytes.
|
||||
#[staticmethod]
|
||||
fn from_bytes(pk_bytes: &[u8], sk_bytes: &[u8]) -> PyResult<Self> {
|
||||
let pk = soliton::identity::IdentityPublicKey::from_bytes(pk_bytes.to_vec())
|
||||
.map_err(to_py_err)?;
|
||||
let sk = soliton::identity::IdentitySecretKey::from_bytes(sk_bytes.to_vec())
|
||||
.map_err(to_py_err)?;
|
||||
Ok(Self { pk, sk: Some(sk) })
|
||||
}
|
||||
|
||||
/// Reconstruct a public-key-only identity (cannot sign).
|
||||
#[staticmethod]
|
||||
fn from_public_bytes(pk_bytes: &[u8]) -> PyResult<Self> {
|
||||
let pk = soliton::identity::IdentityPublicKey::from_bytes(pk_bytes.to_vec())
|
||||
.map_err(to_py_err)?;
|
||||
Ok(Self { pk, sk: None })
|
||||
}
|
||||
|
||||
/// Public key bytes.
|
||||
fn public_key<'py>(&self, py: Python<'py>) -> Py<PyBytes> {
|
||||
PyBytes::new(py, self.pk.as_bytes()).into()
|
||||
}
|
||||
|
||||
/// Secret key bytes. Raises if this is a public-key-only identity.
|
||||
fn secret_key<'py>(&self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
|
||||
let sk = self
|
||||
.sk
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("no secret key"))?;
|
||||
Ok(PyBytes::new(py, sk.as_bytes()).into())
|
||||
}
|
||||
|
||||
/// SHA3-256 fingerprint of the public key (32 bytes).
|
||||
fn fingerprint<'py>(&self, py: Python<'py>) -> Py<PyBytes> {
|
||||
let fp = soliton::primitives::sha3_256::hash(self.pk.as_bytes());
|
||||
PyBytes::new(py, &fp).into()
|
||||
}
|
||||
|
||||
/// Hex-encoded fingerprint.
|
||||
fn fingerprint_hex(&self) -> String {
|
||||
soliton::primitives::sha3_256::fingerprint_hex(self.pk.as_bytes())
|
||||
}
|
||||
|
||||
/// Hybrid sign (Ed25519 + ML-DSA-65).
|
||||
fn sign<'py>(&self, py: Python<'py>, message: &[u8]) -> PyResult<Py<PyBytes>> {
|
||||
let sk = self
|
||||
.sk
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("no secret key"))?;
|
||||
let sig = soliton::identity::hybrid_sign(sk, message).map_err(to_py_err)?;
|
||||
Ok(PyBytes::new(py, sig.as_bytes()).into())
|
||||
}
|
||||
|
||||
/// Verify a hybrid signature against this identity's public key.
|
||||
fn verify(&self, message: &[u8], signature: &[u8]) -> PyResult<()> {
|
||||
let sig = soliton::identity::HybridSignature::from_bytes(signature.to_vec())
|
||||
.map_err(to_py_err)?;
|
||||
soliton::identity::hybrid_verify(&self.pk, message, &sig).map_err(to_py_err)
|
||||
}
|
||||
|
||||
/// Zeroize the secret key immediately.
|
||||
fn close(&mut self) {
|
||||
self.sk = None;
|
||||
}
|
||||
|
||||
fn __enter__(slf: Py<Self>) -> Py<Self> {
|
||||
slf
|
||||
}
|
||||
|
||||
fn __exit__(
|
||||
&mut self,
|
||||
_exc_type: Option<&Bound<'_, PyAny>>,
|
||||
_exc_val: Option<&Bound<'_, PyAny>>,
|
||||
_exc_tb: Option<&Bound<'_, PyAny>>,
|
||||
) {
|
||||
self.close();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add_class::<Identity>()?;
|
||||
Ok(())
|
||||
}
|
||||
424
soliton_py/src/kex.rs
Normal file
424
soliton_py/src/kex.rs
Normal file
|
|
@ -0,0 +1,424 @@
|
|||
//! LO-KEX: asynchronous key exchange (KEM-based, similar to X3DH).
|
||||
|
||||
use pyo3::prelude::*;
|
||||
use pyo3::types::PyBytes;
|
||||
|
||||
use crate::errors::to_py_err;
|
||||
|
||||
/// Sign a pre-key with the identity key.
|
||||
///
|
||||
/// Returns the hybrid signature bytes (3373 bytes).
|
||||
#[pyfunction]
|
||||
fn kex_sign_prekey<'py>(py: Python<'py>, ik_sk: &[u8], spk_pub: &[u8]) -> PyResult<Py<PyBytes>> {
|
||||
let sk = soliton::identity::IdentitySecretKey::from_bytes(ik_sk.to_vec()).map_err(to_py_err)?;
|
||||
let spk =
|
||||
soliton::primitives::xwing::PublicKey::from_bytes(spk_pub.to_vec()).map_err(to_py_err)?;
|
||||
let sig = soliton::kex::sign_prekey(&sk, &spk).map_err(to_py_err)?;
|
||||
Ok(PyBytes::new(py, sig.as_bytes()).into())
|
||||
}
|
||||
|
||||
/// Verify a pre-key bundle.
|
||||
///
|
||||
/// Args:
|
||||
/// bundle_ik_pk: Identity public key from the bundle.
|
||||
/// known_ik_pk: Known identity public key for this peer.
|
||||
/// spk_pub: Signed pre-key public key (1216 bytes).
|
||||
/// spk_id: Signed pre-key ID.
|
||||
/// spk_sig: Hybrid signature over spk_pub (3373 bytes).
|
||||
/// crypto_version: Protocol version string (e.g. "lo-crypto-v1").
|
||||
/// opk_pub: Optional one-time pre-key public key.
|
||||
/// opk_id: Optional one-time pre-key ID.
|
||||
///
|
||||
/// Raises ``BundleVerificationError`` on failure.
|
||||
#[pyfunction]
|
||||
#[pyo3(signature = (bundle_ik_pk, known_ik_pk, spk_pub, spk_id, spk_sig, crypto_version, opk_pub=None, opk_id=None))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn kex_verify_bundle(
|
||||
bundle_ik_pk: &[u8],
|
||||
known_ik_pk: &[u8],
|
||||
spk_pub: &[u8],
|
||||
spk_id: u32,
|
||||
spk_sig: &[u8],
|
||||
crypto_version: &str,
|
||||
opk_pub: Option<&[u8]>,
|
||||
opk_id: Option<u32>,
|
||||
) -> PyResult<()> {
|
||||
let bik = soliton::identity::IdentityPublicKey::from_bytes(bundle_ik_pk.to_vec())
|
||||
.map_err(to_py_err)?;
|
||||
let kik = soliton::identity::IdentityPublicKey::from_bytes(known_ik_pk.to_vec())
|
||||
.map_err(to_py_err)?;
|
||||
let spk =
|
||||
soliton::primitives::xwing::PublicKey::from_bytes(spk_pub.to_vec()).map_err(to_py_err)?;
|
||||
let sig =
|
||||
soliton::identity::HybridSignature::from_bytes(spk_sig.to_vec()).map_err(to_py_err)?;
|
||||
|
||||
let opk = match opk_pub {
|
||||
Some(data) => Some(
|
||||
soliton::primitives::xwing::PublicKey::from_bytes(data.to_vec()).map_err(to_py_err)?,
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let bundle = soliton::kex::PreKeyBundle {
|
||||
ik_pub: bik,
|
||||
crypto_version: crypto_version.to_string(),
|
||||
spk_pub: spk,
|
||||
spk_id,
|
||||
spk_sig: sig,
|
||||
opk_pub: opk,
|
||||
opk_id,
|
||||
};
|
||||
|
||||
// verify_bundle consumes the bundle and returns VerifiedBundle on success.
|
||||
soliton::kex::verify_bundle(bundle, &kik).map_err(to_py_err)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Result of session initiation (Alice's side).
|
||||
///
|
||||
/// Contains the session init data to send to Bob, plus secret keys for
|
||||
/// ratchet initialization. Use ``take_root_key`` and ``take_initial_chain_key``
|
||||
/// to extract keys (destructive — second call returns zeros).
|
||||
#[pyclass]
|
||||
pub struct InitiatedSession {
|
||||
inner: Option<soliton::kex::InitiatedSession>,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl InitiatedSession {
|
||||
/// Encoded session init message bytes.
|
||||
fn session_init_encoded<'py>(&self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
|
||||
let encoded = soliton::kex::encode_session_init(&s.session_init).map_err(to_py_err)?;
|
||||
Ok(PyBytes::new(py, &encoded).into())
|
||||
}
|
||||
|
||||
/// Extract root key (32 bytes). Destructive — zeroed after first call.
|
||||
fn take_root_key<'py>(&mut self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_mut()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
|
||||
let rk = s.take_root_key();
|
||||
Ok(PyBytes::new(py, &*rk).into())
|
||||
}
|
||||
|
||||
/// Extract initial chain key (32 bytes). Destructive — zeroed after first call.
|
||||
fn take_initial_chain_key<'py>(&mut self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_mut()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
|
||||
let ck = s.take_initial_chain_key();
|
||||
Ok(PyBytes::new(py, &*ck).into())
|
||||
}
|
||||
|
||||
/// Alice's ephemeral public key bytes (1216 bytes).
|
||||
fn ek_pk<'py>(&self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
|
||||
Ok(PyBytes::new(py, s.ek_pk.as_bytes()).into())
|
||||
}
|
||||
|
||||
/// Alice's ephemeral secret key bytes (2432 bytes).
|
||||
fn ek_sk<'py>(&self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
|
||||
Ok(PyBytes::new(py, s.ek_sk().as_bytes()).into())
|
||||
}
|
||||
|
||||
/// Sender hybrid signature bytes (3373 bytes).
|
||||
fn sender_sig<'py>(&self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
|
||||
Ok(PyBytes::new(py, s.sender_sig.as_bytes()).into())
|
||||
}
|
||||
|
||||
/// Whether an OPK was used.
|
||||
fn opk_used(&self) -> PyResult<bool> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
|
||||
Ok(s.opk_used)
|
||||
}
|
||||
|
||||
/// Sender fingerprint (SHA3-256 of Alice's IK).
|
||||
fn sender_fingerprint<'py>(&self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
|
||||
Ok(PyBytes::new(py, &s.session_init.sender_ik_fingerprint).into())
|
||||
}
|
||||
|
||||
/// Recipient fingerprint (SHA3-256 of Bob's IK).
|
||||
fn recipient_fingerprint<'py>(&self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
|
||||
Ok(PyBytes::new(py, &s.session_init.recipient_ik_fingerprint).into())
|
||||
}
|
||||
|
||||
fn close(&mut self) {
|
||||
self.inner = None;
|
||||
}
|
||||
|
||||
fn __enter__(slf: Py<Self>) -> Py<Self> {
|
||||
slf
|
||||
}
|
||||
|
||||
fn __exit__(
|
||||
&mut self,
|
||||
_exc_type: Option<&Bound<'_, PyAny>>,
|
||||
_exc_val: Option<&Bound<'_, PyAny>>,
|
||||
_exc_tb: Option<&Bound<'_, PyAny>>,
|
||||
) {
|
||||
self.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// Initiate a session (Alice's side).
|
||||
///
|
||||
/// Args:
|
||||
/// alice_ik_pk: Alice's identity public key.
|
||||
/// alice_ik_sk: Alice's identity secret key.
|
||||
/// bundle_ik_pk: Bob's identity public key (from bundle).
|
||||
/// spk_pub: Bob's signed pre-key public key.
|
||||
/// spk_id: Bob's signed pre-key ID.
|
||||
/// spk_sig: Hybrid signature over spk_pub.
|
||||
/// crypto_version: Protocol version string.
|
||||
/// opk_pub: Optional one-time pre-key public key.
|
||||
/// opk_id: Optional one-time pre-key ID.
|
||||
#[pyfunction]
|
||||
#[pyo3(signature = (alice_ik_pk, alice_ik_sk, bundle_ik_pk, spk_pub, spk_id, spk_sig, crypto_version, opk_pub=None, opk_id=None))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn kex_initiate(
|
||||
alice_ik_pk: &[u8],
|
||||
alice_ik_sk: &[u8],
|
||||
bundle_ik_pk: &[u8],
|
||||
spk_pub: &[u8],
|
||||
spk_id: u32,
|
||||
spk_sig: &[u8],
|
||||
crypto_version: &str,
|
||||
opk_pub: Option<&[u8]>,
|
||||
opk_id: Option<u32>,
|
||||
) -> PyResult<InitiatedSession> {
|
||||
let a_pk = soliton::identity::IdentityPublicKey::from_bytes(alice_ik_pk.to_vec())
|
||||
.map_err(to_py_err)?;
|
||||
let a_sk = soliton::identity::IdentitySecretKey::from_bytes(alice_ik_sk.to_vec())
|
||||
.map_err(to_py_err)?;
|
||||
let b_pk = soliton::identity::IdentityPublicKey::from_bytes(bundle_ik_pk.to_vec())
|
||||
.map_err(to_py_err)?;
|
||||
let spk =
|
||||
soliton::primitives::xwing::PublicKey::from_bytes(spk_pub.to_vec()).map_err(to_py_err)?;
|
||||
let sig =
|
||||
soliton::identity::HybridSignature::from_bytes(spk_sig.to_vec()).map_err(to_py_err)?;
|
||||
|
||||
let opk = match opk_pub {
|
||||
Some(data) => Some(
|
||||
soliton::primitives::xwing::PublicKey::from_bytes(data.to_vec()).map_err(to_py_err)?,
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
|
||||
// Clone Bob's PK before moving it into the bundle — verify_bundle
|
||||
// consumes the bundle but needs the known IK as a separate reference.
|
||||
let known_ik = soliton::identity::IdentityPublicKey::from_bytes(bundle_ik_pk.to_vec())
|
||||
.map_err(to_py_err)?;
|
||||
|
||||
let bundle = soliton::kex::PreKeyBundle {
|
||||
ik_pub: b_pk,
|
||||
crypto_version: crypto_version.to_string(),
|
||||
spk_pub: spk,
|
||||
spk_id,
|
||||
spk_sig: sig,
|
||||
opk_pub: opk,
|
||||
opk_id,
|
||||
};
|
||||
|
||||
// verify_bundle checks that the bundle's IK matches known_ik (Bob's PK)
|
||||
// and that the SPK signature is valid. The TOFU check (whether Bob's PK
|
||||
// is the one the caller trusts) is the caller's responsibility.
|
||||
let verified = soliton::kex::verify_bundle(bundle, &known_ik).map_err(to_py_err)?;
|
||||
|
||||
let session = soliton::kex::initiate_session(&a_pk, &a_sk, &verified).map_err(to_py_err)?;
|
||||
Ok(InitiatedSession {
|
||||
inner: Some(session),
|
||||
})
|
||||
}
|
||||
|
||||
/// Result of session receipt (Bob's side).
|
||||
#[pyclass]
|
||||
pub struct ReceivedSession {
|
||||
inner: Option<soliton::kex::ReceivedSession>,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl ReceivedSession {
|
||||
/// Extract root key (32 bytes). Destructive.
|
||||
fn take_root_key<'py>(&mut self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_mut()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
|
||||
let rk = s.take_root_key();
|
||||
Ok(PyBytes::new(py, &*rk).into())
|
||||
}
|
||||
|
||||
/// Extract initial chain key (32 bytes). Destructive.
|
||||
fn take_initial_chain_key<'py>(&mut self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_mut()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
|
||||
let ck = s.take_initial_chain_key();
|
||||
Ok(PyBytes::new(py, &*ck).into())
|
||||
}
|
||||
|
||||
/// Peer's ephemeral public key (1216 bytes).
|
||||
fn peer_ek<'py>(&self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
|
||||
let s = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("session consumed"))?;
|
||||
Ok(PyBytes::new(py, s.peer_ek.as_bytes()).into())
|
||||
}
|
||||
|
||||
fn close(&mut self) {
|
||||
self.inner = None;
|
||||
}
|
||||
|
||||
fn __enter__(slf: Py<Self>) -> Py<Self> {
|
||||
slf
|
||||
}
|
||||
|
||||
fn __exit__(
|
||||
&mut self,
|
||||
_exc_type: Option<&Bound<'_, PyAny>>,
|
||||
_exc_val: Option<&Bound<'_, PyAny>>,
|
||||
_exc_tb: Option<&Bound<'_, PyAny>>,
|
||||
) {
|
||||
self.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// Receive a session (Bob's side).
|
||||
///
|
||||
/// Args:
|
||||
/// bob_ik_pk: Bob's identity public key.
|
||||
/// bob_ik_sk: Bob's identity secret key.
|
||||
/// alice_ik_pk: Alice's identity public key.
|
||||
/// session_init_encoded: Encoded session init bytes from Alice.
|
||||
/// sender_sig: Alice's hybrid signature (3373 bytes).
|
||||
/// spk_sk: Bob's signed pre-key secret key.
|
||||
/// opk_sk: Optional one-time pre-key secret key.
|
||||
#[pyfunction]
|
||||
#[pyo3(signature = (bob_ik_pk, bob_ik_sk, alice_ik_pk, session_init_encoded, sender_sig, spk_sk, opk_sk=None))]
|
||||
fn kex_receive(
|
||||
bob_ik_pk: &[u8],
|
||||
bob_ik_sk: &[u8],
|
||||
alice_ik_pk: &[u8],
|
||||
session_init_encoded: &[u8],
|
||||
sender_sig: &[u8],
|
||||
spk_sk: &[u8],
|
||||
opk_sk: Option<&[u8]>,
|
||||
) -> PyResult<ReceivedSession> {
|
||||
let b_pk =
|
||||
soliton::identity::IdentityPublicKey::from_bytes(bob_ik_pk.to_vec()).map_err(to_py_err)?;
|
||||
let b_sk =
|
||||
soliton::identity::IdentitySecretKey::from_bytes(bob_ik_sk.to_vec()).map_err(to_py_err)?;
|
||||
let a_pk = soliton::identity::IdentityPublicKey::from_bytes(alice_ik_pk.to_vec())
|
||||
.map_err(to_py_err)?;
|
||||
let si = soliton::kex::decode_session_init(session_init_encoded).map_err(to_py_err)?;
|
||||
let sig =
|
||||
soliton::identity::HybridSignature::from_bytes(sender_sig.to_vec()).map_err(to_py_err)?;
|
||||
let spk_secret =
|
||||
soliton::primitives::xwing::SecretKey::from_bytes(spk_sk.to_vec()).map_err(to_py_err)?;
|
||||
let opk_secret = match opk_sk {
|
||||
Some(data) => Some(
|
||||
soliton::primitives::xwing::SecretKey::from_bytes(data.to_vec()).map_err(to_py_err)?,
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let session = soliton::kex::receive_session(
|
||||
&b_pk,
|
||||
&b_sk,
|
||||
&a_pk,
|
||||
&si,
|
||||
&sig,
|
||||
&spk_secret,
|
||||
opk_secret.as_ref(),
|
||||
)
|
||||
.map_err(to_py_err)?;
|
||||
Ok(ReceivedSession {
|
||||
inner: Some(session),
|
||||
})
|
||||
}
|
||||
|
||||
/// Encode a session init to wire bytes.
|
||||
#[pyfunction]
|
||||
fn kex_encode_session_init<'py>(
|
||||
py: Python<'py>,
|
||||
session_init_encoded: &[u8],
|
||||
) -> PyResult<Py<PyBytes>> {
|
||||
// This re-encodes from decoded form — useful for round-trip testing.
|
||||
let si = soliton::kex::decode_session_init(session_init_encoded).map_err(to_py_err)?;
|
||||
let encoded = soliton::kex::encode_session_init(&si).map_err(to_py_err)?;
|
||||
Ok(PyBytes::new(py, &encoded).into())
|
||||
}
|
||||
|
||||
/// Decode session init from wire bytes.
|
||||
///
|
||||
/// Returns a dict with the decoded fields.
|
||||
#[pyfunction]
|
||||
fn kex_decode_session_init<'py>(py: Python<'py>, data: &[u8]) -> PyResult<Py<PyBytes>> {
|
||||
// For simplicity, just validate it decodes and return the same bytes.
|
||||
// The full structured access is via kex_receive which takes encoded bytes.
|
||||
let _si = soliton::kex::decode_session_init(data).map_err(to_py_err)?;
|
||||
Ok(PyBytes::new(py, data).into())
|
||||
}
|
||||
|
||||
/// Build first-message AAD from fingerprints and encoded session init.
|
||||
#[pyfunction]
|
||||
fn kex_build_first_message_aad<'py>(
|
||||
py: Python<'py>,
|
||||
sender_fp: &[u8],
|
||||
recipient_fp: &[u8],
|
||||
session_init_encoded: &[u8],
|
||||
) -> PyResult<Py<PyBytes>> {
|
||||
if sender_fp.len() != 32 || recipient_fp.len() != 32 {
|
||||
return Err(crate::errors::InvalidLengthError::new_err(
|
||||
"fingerprints must be 32 bytes",
|
||||
));
|
||||
}
|
||||
let sfp: &[u8; 32] = sender_fp.try_into().unwrap();
|
||||
let rfp: &[u8; 32] = recipient_fp.try_into().unwrap();
|
||||
let aad = soliton::kex::build_first_message_aad_from_encoded(sfp, rfp, session_init_encoded)
|
||||
.map_err(to_py_err)?;
|
||||
Ok(PyBytes::new(py, &aad).into())
|
||||
}
|
||||
|
||||
pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add_class::<InitiatedSession>()?;
|
||||
m.add_class::<ReceivedSession>()?;
|
||||
m.add_function(wrap_pyfunction!(kex_sign_prekey, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(kex_verify_bundle, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(kex_initiate, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(kex_receive, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(kex_encode_session_init, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(kex_decode_session_init, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(kex_build_first_message_aad, m)?)?;
|
||||
Ok(())
|
||||
}
|
||||
39
soliton_py/src/lib.rs
Normal file
39
soliton_py/src/lib.rs
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
//! Python bindings for libsoliton via PyO3.
|
||||
//!
|
||||
//! This crate wraps the core Rust API (not the CAPI) to provide a safe,
|
||||
//! ergonomic Python interface. The Zig binding covers the CAPI path.
|
||||
|
||||
use pyo3::prelude::*;
|
||||
|
||||
mod auth;
|
||||
mod call;
|
||||
mod errors;
|
||||
mod identity;
|
||||
mod kex;
|
||||
mod primitives;
|
||||
mod ratchet;
|
||||
mod storage;
|
||||
mod stream;
|
||||
mod verification;
|
||||
|
||||
/// libsoliton — post-quantum cryptographic library.
|
||||
#[pymodule]
|
||||
fn _native(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
// Version
|
||||
m.add("__version__", env!("CARGO_PKG_VERSION"))?;
|
||||
m.add("VERSION", soliton::VERSION)?;
|
||||
|
||||
// Register submodules.
|
||||
errors::register(m)?;
|
||||
primitives::register(m)?;
|
||||
identity::register(m)?;
|
||||
auth::register(m)?;
|
||||
kex::register(m)?;
|
||||
ratchet::register(m)?;
|
||||
storage::register(m)?;
|
||||
stream::register(m)?;
|
||||
call::register(m)?;
|
||||
verification::register(m)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
77
soliton_py/src/primitives.rs
Normal file
77
soliton_py/src/primitives.rs
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
//! Primitive cryptographic operations: SHA3-256, HMAC, HKDF.
|
||||
|
||||
use pyo3::prelude::*;
|
||||
use pyo3::types::PyBytes;
|
||||
|
||||
use crate::errors::to_py_err;
|
||||
|
||||
/// SHA3-256 hash.
|
||||
#[pyfunction]
|
||||
fn sha3_256(py: Python<'_>, data: &[u8]) -> PyResult<Py<PyBytes>> {
|
||||
let hash = soliton::primitives::sha3_256::hash(data);
|
||||
Ok(PyBytes::new(py, &hash).into())
|
||||
}
|
||||
|
||||
/// SHA3-256 hex fingerprint of a public key or arbitrary data.
|
||||
#[pyfunction]
|
||||
fn fingerprint_hex(data: &[u8]) -> String {
|
||||
soliton::primitives::sha3_256::fingerprint_hex(data)
|
||||
}
|
||||
|
||||
/// HMAC-SHA3-256.
|
||||
#[pyfunction]
|
||||
fn hmac_sha3_256(py: Python<'_>, key: &[u8], data: &[u8]) -> PyResult<Py<PyBytes>> {
|
||||
let tag = soliton::primitives::hmac::hmac_sha3_256(key, data);
|
||||
Ok(PyBytes::new(py, &tag).into())
|
||||
}
|
||||
|
||||
/// Constant-time HMAC-SHA3-256 verification.
|
||||
#[pyfunction]
|
||||
fn hmac_sha3_256_verify(a: &[u8], b: &[u8]) -> PyResult<bool> {
|
||||
if a.len() != 32 || b.len() != 32 {
|
||||
return Err(crate::errors::InvalidLengthError::new_err(
|
||||
"both inputs must be 32 bytes",
|
||||
));
|
||||
}
|
||||
let a: &[u8; 32] = a.try_into().unwrap();
|
||||
let b: &[u8; 32] = b.try_into().unwrap();
|
||||
Ok(soliton::primitives::hmac::hmac_sha3_256_verify_raw(a, b))
|
||||
}
|
||||
|
||||
/// HKDF-SHA3-256 extract-and-expand.
|
||||
#[pyfunction]
|
||||
#[pyo3(signature = (salt, ikm, info, *, length))]
|
||||
fn hkdf_sha3_256(
|
||||
py: Python<'_>,
|
||||
salt: &[u8],
|
||||
ikm: &[u8],
|
||||
info: &[u8],
|
||||
length: usize,
|
||||
) -> PyResult<Py<PyBytes>> {
|
||||
let mut out = vec![0u8; length];
|
||||
soliton::primitives::hkdf::hkdf_sha3_256(salt, ikm, info, &mut out).map_err(to_py_err)?;
|
||||
Ok(PyBytes::new(py, &out).into())
|
||||
}
|
||||
|
||||
/// Generate an X-Wing keypair.
|
||||
///
|
||||
/// Returns (public_key, secret_key) as a tuple of bytes.
|
||||
/// Public key is 1216 bytes, secret key is 2432 bytes.
|
||||
#[pyfunction]
|
||||
fn xwing_keygen(py: Python<'_>) -> PyResult<(Py<PyBytes>, Py<PyBytes>)> {
|
||||
let (pk, sk) = soliton::primitives::xwing::keygen().map_err(to_py_err)?;
|
||||
Ok((
|
||||
PyBytes::new(py, pk.as_bytes()).into(),
|
||||
PyBytes::new(py, sk.as_bytes()).into(),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add_function(wrap_pyfunction!(sha3_256, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(fingerprint_hex, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(hmac_sha3_256, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(hmac_sha3_256_verify, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(hkdf_sha3_256, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(xwing_keygen, m)?)?;
|
||||
Ok(())
|
||||
}
|
||||
349
soliton_py/src/ratchet.rs
Normal file
349
soliton_py/src/ratchet.rs
Normal file
|
|
@ -0,0 +1,349 @@
|
|||
//! Double ratchet session: encrypt, decrypt, serialize, deserialize.
|
||||
|
||||
use pyo3::prelude::*;
|
||||
use pyo3::types::PyBytes;
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use crate::call::CallKeys;
|
||||
use crate::errors::to_py_err;
|
||||
|
||||
/// Double ratchet session state.
|
||||
///
|
||||
/// Manages the symmetric ratchet for ongoing message encryption/decryption.
|
||||
/// Initialized after KEX completes (from root_key + chain_key + peer_ek).
|
||||
///
|
||||
/// Use as a context manager for automatic zeroization::
|
||||
///
|
||||
/// with Ratchet.init_alice(root_key, chain_key, local_fp, remote_fp, peer_ek, ek_sk) as r:
|
||||
/// header, ciphertext = r.encrypt(b"hello")
|
||||
#[pyclass]
|
||||
pub struct Ratchet {
|
||||
inner: Option<soliton::ratchet::RatchetState>,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl Ratchet {
|
||||
/// Initialize Alice's side (initiator).
|
||||
#[staticmethod]
|
||||
fn init_alice(
|
||||
root_key: &[u8],
|
||||
chain_key: &[u8],
|
||||
local_fp: &[u8],
|
||||
remote_fp: &[u8],
|
||||
peer_ek: &[u8],
|
||||
ek_sk: &[u8],
|
||||
) -> PyResult<Self> {
|
||||
let mut rk = to_32("root_key", root_key)?;
|
||||
let mut ck = to_32("chain_key", chain_key)?;
|
||||
let lfp = to_32("local_fp", local_fp)?;
|
||||
let rfp = to_32("remote_fp", remote_fp)?;
|
||||
|
||||
let ek_pub = soliton::primitives::xwing::PublicKey::from_bytes(peer_ek.to_vec())
|
||||
.map_err(to_py_err)?;
|
||||
let ek_secret =
|
||||
soliton::primitives::xwing::SecretKey::from_bytes(ek_sk.to_vec()).map_err(to_py_err)?;
|
||||
|
||||
let state = soliton::ratchet::RatchetState::init_alice(rk, ck, lfp, rfp, ek_pub, ek_secret)
|
||||
.map_err(to_py_err)?;
|
||||
|
||||
rk.zeroize();
|
||||
ck.zeroize();
|
||||
Ok(Self { inner: Some(state) })
|
||||
}
|
||||
|
||||
/// Initialize Bob's side (responder).
|
||||
#[staticmethod]
|
||||
fn init_bob(
|
||||
root_key: &[u8],
|
||||
chain_key: &[u8],
|
||||
local_fp: &[u8],
|
||||
remote_fp: &[u8],
|
||||
peer_ek: &[u8],
|
||||
) -> PyResult<Self> {
|
||||
let mut rk = to_32("root_key", root_key)?;
|
||||
let mut ck = to_32("chain_key", chain_key)?;
|
||||
let lfp = to_32("local_fp", local_fp)?;
|
||||
let rfp = to_32("remote_fp", remote_fp)?;
|
||||
|
||||
let ek_pub = soliton::primitives::xwing::PublicKey::from_bytes(peer_ek.to_vec())
|
||||
.map_err(to_py_err)?;
|
||||
|
||||
let state = soliton::ratchet::RatchetState::init_bob(rk, ck, lfp, rfp, ek_pub)
|
||||
.map_err(to_py_err)?;
|
||||
|
||||
rk.zeroize();
|
||||
ck.zeroize();
|
||||
Ok(Self { inner: Some(state) })
|
||||
}
|
||||
|
||||
/// Encrypt a plaintext message.
|
||||
///
|
||||
/// Returns:
|
||||
/// Tuple of (header_bytes, ciphertext). header_bytes is the serialized
|
||||
/// RatchetHeader (ratchet_pk + optional kem_ct + n + pn); ciphertext is
|
||||
/// the AEAD output. Both must be sent to the recipient.
|
||||
fn encrypt<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
plaintext: &[u8],
|
||||
) -> PyResult<(Py<PyBytes>, Py<PyBytes>)> {
|
||||
let state = self.inner.as_mut().ok_or_else(|| {
|
||||
crate::errors::InvalidDataError::new_err("ratchet consumed or closed")
|
||||
})?;
|
||||
let msg = state.encrypt(plaintext).map_err(to_py_err)?;
|
||||
|
||||
// Serialize the header to bytes for transport.
|
||||
let header_bytes = encode_header(&msg.header);
|
||||
Ok((
|
||||
PyBytes::new(py, &header_bytes).into(),
|
||||
PyBytes::new(py, &msg.ciphertext).into(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Decrypt a received message.
|
||||
///
|
||||
/// Args:
|
||||
/// header: Serialized RatchetHeader bytes (from sender's encrypt()).
|
||||
/// ciphertext: AEAD ciphertext bytes.
|
||||
///
|
||||
/// Returns:
|
||||
/// Decrypted plaintext bytes.
|
||||
fn decrypt<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
header: &[u8],
|
||||
ciphertext: &[u8],
|
||||
) -> PyResult<Py<PyBytes>> {
|
||||
let state = self.inner.as_mut().ok_or_else(|| {
|
||||
crate::errors::InvalidDataError::new_err("ratchet consumed or closed")
|
||||
})?;
|
||||
let rh = decode_header(header)?;
|
||||
let pt = state.decrypt(&rh, ciphertext).map_err(to_py_err)?;
|
||||
Ok(PyBytes::new(py, &pt).into())
|
||||
}
|
||||
|
||||
/// Encrypt the first message (pre-ratchet, uses initial chain key).
|
||||
///
|
||||
/// This is a static method — called before the ratchet is initialized.
|
||||
///
|
||||
/// Args:
|
||||
/// chain_key: 32-byte initial chain key from KEX.
|
||||
/// plaintext: First application message.
|
||||
/// aad: Additional authenticated data (from build_first_message_aad).
|
||||
///
|
||||
/// Returns:
|
||||
/// Tuple of (encrypted_payload, ratchet_init_key). Pass ratchet_init_key
|
||||
/// as chain_key to init_alice/init_bob.
|
||||
#[staticmethod]
|
||||
fn encrypt_first_message<'py>(
|
||||
py: Python<'py>,
|
||||
chain_key: &[u8],
|
||||
plaintext: &[u8],
|
||||
aad: &[u8],
|
||||
) -> PyResult<(Py<PyBytes>, Py<PyBytes>)> {
|
||||
let ck = zeroizing_32("chain_key", chain_key)?;
|
||||
let (ct, rik) = soliton::ratchet::RatchetState::encrypt_first_message(ck, plaintext, aad)
|
||||
.map_err(to_py_err)?;
|
||||
Ok((PyBytes::new(py, &ct).into(), PyBytes::new(py, &*rik).into()))
|
||||
}
|
||||
|
||||
/// Decrypt the first message (pre-ratchet).
|
||||
///
|
||||
/// Returns:
|
||||
/// Tuple of (plaintext, ratchet_init_key).
|
||||
#[staticmethod]
|
||||
fn decrypt_first_message<'py>(
|
||||
py: Python<'py>,
|
||||
chain_key: &[u8],
|
||||
encrypted_payload: &[u8],
|
||||
aad: &[u8],
|
||||
) -> PyResult<(Py<PyBytes>, Py<PyBytes>)> {
|
||||
let ck = zeroizing_32("chain_key", chain_key)?;
|
||||
let (pt, rik) =
|
||||
soliton::ratchet::RatchetState::decrypt_first_message(ck, encrypted_payload, aad)
|
||||
.map_err(to_py_err)?;
|
||||
Ok((PyBytes::new(py, &pt).into(), PyBytes::new(py, &*rik).into()))
|
||||
}
|
||||
|
||||
/// Serialize the ratchet state. Consumes the ratchet.
|
||||
///
|
||||
/// Returns:
|
||||
/// Tuple of (blob, epoch). Persist the blob encrypted (e.g., with
|
||||
/// StorageKeyRing). Store epoch separately for anti-rollback.
|
||||
#[allow(clippy::wrong_self_convention)]
|
||||
fn to_bytes<'py>(&mut self, py: Python<'py>) -> PyResult<(Py<PyBytes>, u64)> {
|
||||
let state = self
|
||||
.inner
|
||||
.take()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("ratchet already consumed"))?;
|
||||
let (blob, epoch) = state.to_bytes().map_err(to_py_err)?;
|
||||
Ok((PyBytes::new(py, &blob).into(), epoch))
|
||||
}
|
||||
|
||||
/// Deserialize ratchet state with anti-rollback protection.
|
||||
///
|
||||
/// Args:
|
||||
/// data: Serialized ratchet blob.
|
||||
/// min_epoch: Minimum acceptable epoch. Use saved_epoch - 1.
|
||||
#[staticmethod]
|
||||
fn from_bytes(data: &[u8], min_epoch: u64) -> PyResult<Self> {
|
||||
let state = soliton::ratchet::RatchetState::from_bytes_with_min_epoch(data, min_epoch)
|
||||
.map_err(to_py_err)?;
|
||||
Ok(Self { inner: Some(state) })
|
||||
}
|
||||
|
||||
/// Whether the ratchet can be serialized (counters not exhausted).
|
||||
fn can_serialize(&self) -> PyResult<bool> {
|
||||
let state = self.inner.as_ref().ok_or_else(|| {
|
||||
crate::errors::InvalidDataError::new_err("ratchet consumed or closed")
|
||||
})?;
|
||||
Ok(state.can_serialize())
|
||||
}
|
||||
|
||||
/// Current epoch number.
|
||||
fn epoch(&self) -> PyResult<u64> {
|
||||
let state = self.inner.as_ref().ok_or_else(|| {
|
||||
crate::errors::InvalidDataError::new_err("ratchet consumed or closed")
|
||||
})?;
|
||||
Ok(state.epoch())
|
||||
}
|
||||
|
||||
/// Reset the ratchet (zeroize all keys). The session is dead after this.
|
||||
fn reset(&mut self) -> PyResult<()> {
|
||||
let state = self.inner.as_mut().ok_or_else(|| {
|
||||
crate::errors::InvalidDataError::new_err("ratchet consumed or closed")
|
||||
})?;
|
||||
state.reset();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Derive call keys for encrypted voice/video.
|
||||
fn derive_call_keys(&self, kem_ss: &[u8], call_id: &[u8]) -> PyResult<CallKeys> {
|
||||
let state = self.inner.as_ref().ok_or_else(|| {
|
||||
crate::errors::InvalidDataError::new_err("ratchet consumed or closed")
|
||||
})?;
|
||||
if kem_ss.len() != 32 {
|
||||
return Err(crate::errors::InvalidLengthError::new_err(
|
||||
"kem_ss must be 32 bytes",
|
||||
));
|
||||
}
|
||||
if call_id.len() != 16 {
|
||||
return Err(crate::errors::InvalidLengthError::new_err(
|
||||
"call_id must be 16 bytes",
|
||||
));
|
||||
}
|
||||
let ss: &[u8; 32] = kem_ss.try_into().unwrap();
|
||||
let cid: &[u8; 16] = call_id.try_into().unwrap();
|
||||
let keys = state.derive_call_keys(ss, cid).map_err(to_py_err)?;
|
||||
Ok(CallKeys::from_inner(keys))
|
||||
}
|
||||
|
||||
fn close(&mut self) {
|
||||
if let Some(mut state) = self.inner.take() {
|
||||
state.reset();
|
||||
}
|
||||
}
|
||||
|
||||
fn __enter__(slf: Py<Self>) -> Py<Self> {
|
||||
slf
|
||||
}
|
||||
|
||||
fn __exit__(
|
||||
&mut self,
|
||||
_exc_type: Option<&Bound<'_, PyAny>>,
|
||||
_exc_val: Option<&Bound<'_, PyAny>>,
|
||||
_exc_tb: Option<&Bound<'_, PyAny>>,
|
||||
) {
|
||||
self.close();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Header serialization ────────────────────────────────────────────────
|
||||
//
|
||||
// Simple wire format for Python: ratchet_pk (1216) + has_kem_ct (1) +
|
||||
// [kem_ct (1120) if present] + n (4 BE) + pn (4 BE).
|
||||
// This matches the CAPI's encode_ratchet_header layout.
|
||||
|
||||
fn encode_header(h: &soliton::ratchet::RatchetHeader) -> Vec<u8> {
|
||||
let pk_bytes = h.ratchet_pk.as_bytes();
|
||||
let has_ct = h.kem_ct.is_some();
|
||||
let size = 1216 + 1 + if has_ct { 2 + 1120 } else { 0 } + 4 + 4;
|
||||
let mut buf = Vec::with_capacity(size);
|
||||
buf.extend_from_slice(pk_bytes);
|
||||
if let Some(ref ct) = h.kem_ct {
|
||||
buf.push(0x01);
|
||||
let ct_bytes = ct.as_bytes();
|
||||
buf.extend_from_slice(&(ct_bytes.len() as u16).to_be_bytes());
|
||||
buf.extend_from_slice(ct_bytes);
|
||||
} else {
|
||||
buf.push(0x00);
|
||||
}
|
||||
buf.extend_from_slice(&h.n.to_be_bytes());
|
||||
buf.extend_from_slice(&h.pn.to_be_bytes());
|
||||
buf
|
||||
}
|
||||
|
||||
fn decode_header(data: &[u8]) -> PyResult<soliton::ratchet::RatchetHeader> {
|
||||
if data.len() < 1216 + 1 + 4 + 4 {
|
||||
return Err(crate::errors::InvalidDataError::new_err("header too short"));
|
||||
}
|
||||
let ratchet_pk = soliton::primitives::xwing::PublicKey::from_bytes(data[..1216].to_vec())
|
||||
.map_err(to_py_err)?;
|
||||
let has_ct = data[1216];
|
||||
if has_ct != 0x00 && has_ct != 0x01 {
|
||||
return Err(crate::errors::InvalidDataError::new_err(
|
||||
"invalid has_kem_ct flag (expected 0x00 or 0x01)",
|
||||
));
|
||||
}
|
||||
let rest = if has_ct == 0x01 {
|
||||
if data.len() < 1216 + 1 + 2 + 1120 + 4 + 4 {
|
||||
return Err(crate::errors::InvalidDataError::new_err(
|
||||
"header too short for kem_ct",
|
||||
));
|
||||
}
|
||||
&data[1216 + 1 + 2 + 1120..]
|
||||
} else {
|
||||
&data[1216 + 1..]
|
||||
};
|
||||
let kem_ct = if has_ct == 0x01 {
|
||||
Some(
|
||||
soliton::primitives::xwing::Ciphertext::from_bytes(
|
||||
data[1216 + 1 + 2..1216 + 1 + 2 + 1120].to_vec(),
|
||||
)
|
||||
.map_err(to_py_err)?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if rest.len() < 8 {
|
||||
return Err(crate::errors::InvalidDataError::new_err(
|
||||
"header missing counters",
|
||||
));
|
||||
}
|
||||
let n = u32::from_be_bytes(rest[..4].try_into().unwrap());
|
||||
let pn = u32::from_be_bytes(rest[4..8].try_into().unwrap());
|
||||
|
||||
Ok(soliton::ratchet::RatchetHeader {
|
||||
ratchet_pk,
|
||||
kem_ct,
|
||||
n,
|
||||
pn,
|
||||
})
|
||||
}
|
||||
|
||||
// ── Helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
fn to_32(name: &str, data: &[u8]) -> PyResult<[u8; 32]> {
|
||||
data.try_into()
|
||||
.map_err(|_| crate::errors::InvalidLengthError::new_err(format!("{name} must be 32 bytes")))
|
||||
}
|
||||
|
||||
fn zeroizing_32(name: &str, data: &[u8]) -> PyResult<zeroize::Zeroizing<[u8; 32]>> {
|
||||
let arr = to_32(name, data)?;
|
||||
Ok(zeroize::Zeroizing::new(arr))
|
||||
}
|
||||
|
||||
pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add_class::<Ratchet>()?;
|
||||
Ok(())
|
||||
}
|
||||
199
soliton_py/src/storage.rs
Normal file
199
soliton_py/src/storage.rs
Normal file
|
|
@ -0,0 +1,199 @@
|
|||
//! Encrypted storage: community blobs and DM queue blobs.
|
||||
|
||||
use pyo3::prelude::*;
|
||||
use pyo3::types::PyBytes;
|
||||
|
||||
use crate::errors::to_py_err;
|
||||
|
||||
/// Encrypted storage key ring.
|
||||
///
|
||||
/// Manages versioned encryption keys for community storage and DM queues.
|
||||
/// Multiple key versions can coexist for key rotation — old keys decrypt
|
||||
/// existing blobs while new keys encrypt new writes.
|
||||
///
|
||||
/// Use as a context manager for automatic zeroization::
|
||||
///
|
||||
/// with soliton.StorageKeyRing(1, key_bytes) as ring:
|
||||
/// blob = ring.encrypt_blob("channel-1", "seg-0", plaintext)
|
||||
/// data = ring.decrypt_blob("channel-1", "seg-0", blob)
|
||||
#[pyclass]
|
||||
pub struct StorageKeyRing {
|
||||
inner: Option<soliton::storage::StorageKeyRing>,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl StorageKeyRing {
|
||||
/// Create a keyring with an initial active key.
|
||||
///
|
||||
/// Args:
|
||||
/// version: Key version (1-255). Version 0 is rejected.
|
||||
/// key: 32-byte encryption key.
|
||||
#[new]
|
||||
fn new(version: u8, key: &[u8]) -> PyResult<Self> {
|
||||
if key.len() != 32 {
|
||||
return Err(crate::errors::InvalidLengthError::new_err(
|
||||
"key must be 32 bytes",
|
||||
));
|
||||
}
|
||||
let key_arr: [u8; 32] = key.try_into().unwrap();
|
||||
let storage_key = soliton::storage::StorageKey::new(version, key_arr).map_err(to_py_err)?;
|
||||
let ring = soliton::storage::StorageKeyRing::new(storage_key).map_err(to_py_err)?;
|
||||
Ok(Self { inner: Some(ring) })
|
||||
}
|
||||
|
||||
/// Add a key to the ring.
|
||||
///
|
||||
/// Args:
|
||||
/// version: Key version (1-255).
|
||||
/// key: 32-byte encryption key.
|
||||
/// make_active: If True, this key becomes the active key for new writes.
|
||||
fn add_key(&mut self, version: u8, key: &[u8], make_active: bool) -> PyResult<()> {
|
||||
if key.len() != 32 {
|
||||
return Err(crate::errors::InvalidLengthError::new_err(
|
||||
"key must be 32 bytes",
|
||||
));
|
||||
}
|
||||
let ring = self
|
||||
.inner
|
||||
.as_mut()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("keyring closed"))?;
|
||||
let key_arr: [u8; 32] = key.try_into().unwrap();
|
||||
let storage_key = soliton::storage::StorageKey::new(version, key_arr).map_err(to_py_err)?;
|
||||
ring.add_key(storage_key, make_active).map_err(to_py_err)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove a key version from the ring.
|
||||
///
|
||||
/// The active version cannot be removed — set a new active key first.
|
||||
fn remove_key(&mut self, version: u8) -> PyResult<()> {
|
||||
let ring = self
|
||||
.inner
|
||||
.as_mut()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("keyring closed"))?;
|
||||
ring.remove_key(version).map_err(to_py_err)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Encrypt a community storage blob.
|
||||
///
|
||||
/// Args:
|
||||
/// channel_id: Channel identifier (bound into AAD).
|
||||
/// segment_id: Segment identifier (bound into AAD).
|
||||
/// plaintext: Data to encrypt.
|
||||
///
|
||||
/// Returns:
|
||||
/// Encrypted blob bytes (self-describing — contains key version).
|
||||
#[pyo3(signature = (channel_id, segment_id, plaintext, compress=false))]
|
||||
fn encrypt_blob<'py>(
|
||||
&self,
|
||||
py: Python<'py>,
|
||||
channel_id: &str,
|
||||
segment_id: &str,
|
||||
plaintext: &[u8],
|
||||
compress: bool,
|
||||
) -> PyResult<Py<PyBytes>> {
|
||||
let ring = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("keyring closed"))?;
|
||||
let key = ring
|
||||
.active_key()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("no active key"))?;
|
||||
let blob = soliton::storage::encrypt_blob(key, plaintext, channel_id, segment_id, compress)
|
||||
.map_err(to_py_err)?;
|
||||
Ok(PyBytes::new(py, &blob).into())
|
||||
}
|
||||
|
||||
/// Decrypt a community storage blob.
|
||||
///
|
||||
/// The blob's embedded key version selects the decryption key from the ring.
|
||||
fn decrypt_blob<'py>(
|
||||
&self,
|
||||
py: Python<'py>,
|
||||
channel_id: &str,
|
||||
segment_id: &str,
|
||||
blob: &[u8],
|
||||
) -> PyResult<Py<PyBytes>> {
|
||||
let ring = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("keyring closed"))?;
|
||||
let pt = soliton::storage::decrypt_blob(ring, blob, channel_id, segment_id)
|
||||
.map_err(to_py_err)?;
|
||||
Ok(PyBytes::new(py, &pt).into())
|
||||
}
|
||||
|
||||
/// Encrypt a DM queue blob.
|
||||
#[pyo3(signature = (recipient_fp, batch_id, plaintext, compress=false))]
|
||||
fn encrypt_dm_queue<'py>(
|
||||
&self,
|
||||
py: Python<'py>,
|
||||
recipient_fp: &[u8],
|
||||
batch_id: &str,
|
||||
plaintext: &[u8],
|
||||
compress: bool,
|
||||
) -> PyResult<Py<PyBytes>> {
|
||||
if recipient_fp.len() != 32 {
|
||||
return Err(crate::errors::InvalidLengthError::new_err(
|
||||
"recipient_fp must be 32 bytes",
|
||||
));
|
||||
}
|
||||
let ring = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("keyring closed"))?;
|
||||
let key = ring
|
||||
.active_key()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("no active key"))?;
|
||||
let fp: &[u8; 32] = recipient_fp.try_into().unwrap();
|
||||
let blob = soliton::storage::encrypt_dm_queue_blob(key, plaintext, fp, batch_id, compress)
|
||||
.map_err(to_py_err)?;
|
||||
Ok(PyBytes::new(py, &blob).into())
|
||||
}
|
||||
|
||||
/// Decrypt a DM queue blob.
|
||||
fn decrypt_dm_queue<'py>(
|
||||
&self,
|
||||
py: Python<'py>,
|
||||
recipient_fp: &[u8],
|
||||
batch_id: &str,
|
||||
blob: &[u8],
|
||||
) -> PyResult<Py<PyBytes>> {
|
||||
if recipient_fp.len() != 32 {
|
||||
return Err(crate::errors::InvalidLengthError::new_err(
|
||||
"recipient_fp must be 32 bytes",
|
||||
));
|
||||
}
|
||||
let ring = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("keyring closed"))?;
|
||||
let fp: &[u8; 32] = recipient_fp.try_into().unwrap();
|
||||
let pt =
|
||||
soliton::storage::decrypt_dm_queue_blob(ring, blob, fp, batch_id).map_err(to_py_err)?;
|
||||
Ok(PyBytes::new(py, &pt).into())
|
||||
}
|
||||
|
||||
fn close(&mut self) {
|
||||
self.inner = None;
|
||||
}
|
||||
|
||||
fn __enter__(slf: Py<Self>) -> Py<Self> {
|
||||
slf
|
||||
}
|
||||
|
||||
fn __exit__(
|
||||
&mut self,
|
||||
_exc_type: Option<&Bound<'_, PyAny>>,
|
||||
_exc_val: Option<&Bound<'_, PyAny>>,
|
||||
_exc_tb: Option<&Bound<'_, PyAny>>,
|
||||
) {
|
||||
self.close();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add_class::<StorageKeyRing>()?;
|
||||
Ok(())
|
||||
}
|
||||
241
soliton_py/src/stream.rs
Normal file
241
soliton_py/src/stream.rs
Normal file
|
|
@ -0,0 +1,241 @@
|
|||
//! Streaming AEAD: chunked encryption/decryption for files and media.
|
||||
|
||||
use pyo3::prelude::*;
|
||||
use pyo3::types::PyBytes;
|
||||
|
||||
use crate::errors::to_py_err;
|
||||
|
||||
/// Streaming encryptor for chunked file/media encryption.
|
||||
///
|
||||
/// Produces a 26-byte header (sent first) and one ciphertext chunk per call
|
||||
/// to ``encrypt_chunk``. Non-final chunks must be exactly 1 MiB of plaintext;
|
||||
/// the final chunk may be shorter.
|
||||
///
|
||||
/// Use as a context manager::
|
||||
///
|
||||
/// with soliton.StreamEncryptor(key) as enc:
|
||||
/// header = enc.header()
|
||||
/// ct1 = enc.encrypt_chunk(data1)
|
||||
/// ct2 = enc.encrypt_chunk(data2, is_last=True)
|
||||
#[pyclass]
|
||||
pub struct StreamEncryptor {
|
||||
inner: Option<soliton::streaming::StreamEncryptor>,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl StreamEncryptor {
|
||||
/// Create a streaming encryptor.
|
||||
///
|
||||
/// Args:
|
||||
/// key: 32-byte encryption key.
|
||||
/// aad: Optional additional authenticated data (bound to all chunks).
|
||||
/// compress: Enable zstd compression per chunk (default False).
|
||||
#[new]
|
||||
#[pyo3(signature = (key, aad=None, compress=false))]
|
||||
fn new(key: &[u8], aad: Option<&[u8]>, compress: bool) -> PyResult<Self> {
|
||||
if key.len() != 32 {
|
||||
return Err(crate::errors::InvalidLengthError::new_err(
|
||||
"key must be 32 bytes",
|
||||
));
|
||||
}
|
||||
let key_arr: &[u8; 32] = key.try_into().unwrap();
|
||||
let aad_bytes = aad.unwrap_or(&[]);
|
||||
let enc = soliton::streaming::stream_encrypt_init(key_arr, aad_bytes, compress)
|
||||
.map_err(to_py_err)?;
|
||||
Ok(Self { inner: Some(enc) })
|
||||
}
|
||||
|
||||
/// The 26-byte stream header. Send this before any chunks.
|
||||
fn header<'py>(&self, py: Python<'py>) -> PyResult<Py<PyBytes>> {
|
||||
let inner = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("encryptor closed"))?;
|
||||
Ok(PyBytes::new(py, &inner.header()).into())
|
||||
}
|
||||
|
||||
/// Encrypt one chunk.
|
||||
///
|
||||
/// Args:
|
||||
/// plaintext: Chunk data. Non-final chunks must be exactly 1,048,576 bytes.
|
||||
/// is_last: True for the final chunk.
|
||||
///
|
||||
/// Returns:
|
||||
/// Encrypted chunk bytes.
|
||||
#[pyo3(signature = (plaintext, is_last=false))]
|
||||
fn encrypt_chunk<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
plaintext: &[u8],
|
||||
is_last: bool,
|
||||
) -> PyResult<Py<PyBytes>> {
|
||||
let inner = self
|
||||
.inner
|
||||
.as_mut()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("encryptor closed"))?;
|
||||
let ct = inner.encrypt_chunk(plaintext, is_last).map_err(to_py_err)?;
|
||||
Ok(PyBytes::new(py, &ct).into())
|
||||
}
|
||||
|
||||
/// Encrypt a specific chunk by index (random access, stateless).
|
||||
fn encrypt_chunk_at<'py>(
|
||||
&self,
|
||||
py: Python<'py>,
|
||||
index: u64,
|
||||
plaintext: &[u8],
|
||||
is_last: bool,
|
||||
) -> PyResult<Py<PyBytes>> {
|
||||
let inner = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("encryptor closed"))?;
|
||||
let ct = inner
|
||||
.encrypt_chunk_at(index, is_last, plaintext)
|
||||
.map_err(to_py_err)?;
|
||||
Ok(PyBytes::new(py, &ct).into())
|
||||
}
|
||||
|
||||
/// Whether the encryptor has been finalized.
|
||||
fn is_finalized(&self) -> PyResult<bool> {
|
||||
let inner = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("encryptor closed"))?;
|
||||
Ok(inner.is_finalized())
|
||||
}
|
||||
|
||||
fn close(&mut self) {
|
||||
self.inner = None;
|
||||
}
|
||||
|
||||
fn __enter__(slf: Py<Self>) -> Py<Self> {
|
||||
slf
|
||||
}
|
||||
|
||||
fn __exit__(
|
||||
&mut self,
|
||||
_exc_type: Option<&Bound<'_, PyAny>>,
|
||||
_exc_val: Option<&Bound<'_, PyAny>>,
|
||||
_exc_tb: Option<&Bound<'_, PyAny>>,
|
||||
) {
|
||||
self.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// Streaming decryptor for chunked file/media decryption.
|
||||
///
|
||||
/// Use as a context manager::
|
||||
///
|
||||
/// with soliton.StreamDecryptor(key, header) as dec:
|
||||
/// pt1, is_last = dec.decrypt_chunk(ct1)
|
||||
/// pt2, is_last = dec.decrypt_chunk(ct2)
|
||||
#[pyclass]
|
||||
pub struct StreamDecryptor {
|
||||
inner: Option<soliton::streaming::StreamDecryptor>,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl StreamDecryptor {
|
||||
/// Create a streaming decryptor.
|
||||
///
|
||||
/// Args:
|
||||
/// key: 32-byte decryption key (same key used for encryption).
|
||||
/// header: 26-byte stream header from the encryptor.
|
||||
/// aad: Optional additional authenticated data (must match encryption).
|
||||
#[new]
|
||||
#[pyo3(signature = (key, header, aad=None))]
|
||||
fn new(key: &[u8], header: &[u8], aad: Option<&[u8]>) -> PyResult<Self> {
|
||||
if key.len() != 32 {
|
||||
return Err(crate::errors::InvalidLengthError::new_err(
|
||||
"key must be 32 bytes",
|
||||
));
|
||||
}
|
||||
if header.len() != 26 {
|
||||
return Err(crate::errors::InvalidLengthError::new_err(
|
||||
"header must be 26 bytes",
|
||||
));
|
||||
}
|
||||
let key_arr: &[u8; 32] = key.try_into().unwrap();
|
||||
let hdr_arr: &[u8; 26] = header.try_into().unwrap();
|
||||
let aad_bytes = aad.unwrap_or(&[]);
|
||||
let dec = soliton::streaming::stream_decrypt_init(key_arr, hdr_arr, aad_bytes)
|
||||
.map_err(to_py_err)?;
|
||||
Ok(Self { inner: Some(dec) })
|
||||
}
|
||||
|
||||
/// Decrypt the next sequential chunk.
|
||||
///
|
||||
/// Returns:
|
||||
/// Tuple of (plaintext: bytes, is_last: bool).
|
||||
fn decrypt_chunk<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
chunk: &[u8],
|
||||
) -> PyResult<(Py<PyBytes>, bool)> {
|
||||
let inner = self
|
||||
.inner
|
||||
.as_mut()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("decryptor closed"))?;
|
||||
let (pt, is_last) = inner.decrypt_chunk(chunk).map_err(to_py_err)?;
|
||||
Ok((PyBytes::new(py, &pt).into(), is_last))
|
||||
}
|
||||
|
||||
/// Decrypt a specific chunk by index (random access).
|
||||
///
|
||||
/// Returns:
|
||||
/// Tuple of (plaintext: bytes, is_last: bool).
|
||||
fn decrypt_chunk_at<'py>(
|
||||
&self,
|
||||
py: Python<'py>,
|
||||
index: u64,
|
||||
chunk: &[u8],
|
||||
) -> PyResult<(Py<PyBytes>, bool)> {
|
||||
let inner = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("decryptor closed"))?;
|
||||
let (pt, is_last) = inner.decrypt_chunk_at(index, chunk).map_err(to_py_err)?;
|
||||
Ok((PyBytes::new(py, &pt).into(), is_last))
|
||||
}
|
||||
|
||||
/// Whether the decryptor has seen the final chunk.
|
||||
fn is_finalized(&self) -> PyResult<bool> {
|
||||
let inner = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("decryptor closed"))?;
|
||||
Ok(inner.is_finalized())
|
||||
}
|
||||
|
||||
/// Next expected sequential chunk index.
|
||||
fn expected_index(&self) -> PyResult<u64> {
|
||||
let inner = self
|
||||
.inner
|
||||
.as_ref()
|
||||
.ok_or_else(|| crate::errors::InvalidDataError::new_err("decryptor closed"))?;
|
||||
Ok(inner.expected_index())
|
||||
}
|
||||
|
||||
fn close(&mut self) {
|
||||
self.inner = None;
|
||||
}
|
||||
|
||||
fn __enter__(slf: Py<Self>) -> Py<Self> {
|
||||
slf
|
||||
}
|
||||
|
||||
fn __exit__(
|
||||
&mut self,
|
||||
_exc_type: Option<&Bound<'_, PyAny>>,
|
||||
_exc_val: Option<&Bound<'_, PyAny>>,
|
||||
_exc_tb: Option<&Bound<'_, PyAny>>,
|
||||
) {
|
||||
self.close();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add_class::<StreamEncryptor>()?;
|
||||
m.add_class::<StreamDecryptor>()?;
|
||||
Ok(())
|
||||
}
|
||||
20
soliton_py/src/verification.rs
Normal file
20
soliton_py/src/verification.rs
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
//! Verification phrases for out-of-band identity verification.
|
||||
|
||||
use pyo3::prelude::*;
|
||||
|
||||
use crate::errors::to_py_err;
|
||||
|
||||
/// Generate a verification phrase from two identity public keys.
|
||||
///
|
||||
/// Each key must be 3200 bytes (full identity public key, not fingerprint).
|
||||
/// Returns a human-readable phrase (6 words from the EFF large wordlist).
|
||||
/// The phrase is symmetric — swapping the keys produces the same phrase.
|
||||
#[pyfunction]
|
||||
fn verification_phrase(pk_a: &[u8], pk_b: &[u8]) -> PyResult<String> {
|
||||
soliton::verification::verification_phrase(pk_a, pk_b).map_err(to_py_err)
|
||||
}
|
||||
|
||||
pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add_function(wrap_pyfunction!(verification_phrase, m)?)?;
|
||||
Ok(())
|
||||
}
|
||||
27
soliton_py/tests/test_auth.py
Normal file
27
soliton_py/tests/test_auth.py
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
"""Tests for LO-Auth challenge-response."""
|
||||
|
||||
import soliton
|
||||
|
||||
|
||||
def test_auth_round_trip():
|
||||
with soliton.Identity.generate() as id:
|
||||
pk = id.public_key()
|
||||
sk = id.secret_key()
|
||||
|
||||
# Server generates challenge.
|
||||
ct, token = soliton.auth_challenge(pk)
|
||||
|
||||
# Client responds.
|
||||
proof = soliton.auth_respond(sk, ct)
|
||||
|
||||
# Server verifies.
|
||||
assert soliton.auth_verify(token, proof) is True
|
||||
|
||||
|
||||
def test_auth_wrong_proof():
|
||||
with soliton.Identity.generate() as id:
|
||||
pk = id.public_key()
|
||||
ct, token = soliton.auth_challenge(pk)
|
||||
# Tampered proof.
|
||||
fake_proof = b"\x00" * 32
|
||||
assert soliton.auth_verify(token, fake_proof) is False
|
||||
78
soliton_py/tests/test_identity.py
Normal file
78
soliton_py/tests/test_identity.py
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
"""Tests for identity key management."""
|
||||
|
||||
import soliton
|
||||
|
||||
|
||||
def test_keygen():
|
||||
with soliton.Identity.generate() as id:
|
||||
pk = id.public_key()
|
||||
sk = id.secret_key()
|
||||
assert len(pk) == 3200 # SOLITON_PUBLIC_KEY_SIZE
|
||||
assert len(sk) == 2496 # SOLITON_SECRET_KEY_SIZE
|
||||
|
||||
|
||||
def test_fingerprint():
|
||||
with soliton.Identity.generate() as id:
|
||||
fp = id.fingerprint()
|
||||
assert len(fp) == 32
|
||||
assert fp != b"\x00" * 32
|
||||
|
||||
|
||||
def test_fingerprint_hex():
|
||||
with soliton.Identity.generate() as id:
|
||||
hex_fp = id.fingerprint_hex()
|
||||
assert len(hex_fp) == 64
|
||||
|
||||
|
||||
def test_sign_verify():
|
||||
with soliton.Identity.generate() as id:
|
||||
msg = b"test message"
|
||||
sig = id.sign(msg)
|
||||
assert len(sig) == 3373 # SOLITON_HYBRID_SIG_SIZE
|
||||
# Verify with same identity.
|
||||
id.verify(msg, sig)
|
||||
|
||||
|
||||
def test_sign_verify_wrong_message():
|
||||
with soliton.Identity.generate() as id:
|
||||
sig = id.sign(b"correct")
|
||||
try:
|
||||
id.verify(b"wrong", sig)
|
||||
assert False, "should have raised"
|
||||
except soliton.VerificationError:
|
||||
pass
|
||||
|
||||
|
||||
def test_context_manager_zeroizes():
|
||||
id = soliton.Identity.generate()
|
||||
with id:
|
||||
_ = id.secret_key()
|
||||
# After exiting context, secret key should be gone.
|
||||
try:
|
||||
id.secret_key()
|
||||
assert False, "should have raised"
|
||||
except soliton.InvalidDataError:
|
||||
pass
|
||||
|
||||
|
||||
def test_from_bytes_roundtrip():
|
||||
with soliton.Identity.generate() as id:
|
||||
pk = id.public_key()
|
||||
sk = id.secret_key()
|
||||
# Reconstruct.
|
||||
id2 = soliton.Identity.from_bytes(pk, sk)
|
||||
msg = b"roundtrip"
|
||||
sig = id2.sign(msg)
|
||||
id2.verify(msg, sig)
|
||||
id2.close()
|
||||
|
||||
|
||||
def test_public_only_cannot_sign():
|
||||
with soliton.Identity.generate() as id:
|
||||
pk = id.public_key()
|
||||
pub_only = soliton.Identity.from_public_bytes(pk)
|
||||
try:
|
||||
pub_only.sign(b"test")
|
||||
assert False, "should have raised"
|
||||
except soliton.InvalidDataError:
|
||||
pass
|
||||
326
soliton_py/tests/test_kex_ratchet.py
Normal file
326
soliton_py/tests/test_kex_ratchet.py
Normal file
|
|
@ -0,0 +1,326 @@
|
|||
"""Tests for KEX, ratchet, and call keys — full session lifecycle."""
|
||||
|
||||
import os
|
||||
import soliton
|
||||
|
||||
|
||||
def test_first_message_round_trip():
|
||||
ck = os.urandom(32)
|
||||
aad = b"test-aad"
|
||||
pt = b"first application message"
|
||||
|
||||
ct, rik_a = soliton.Ratchet.encrypt_first_message(ck, pt, aad)
|
||||
decrypted, rik_b = soliton.Ratchet.decrypt_first_message(ck, ct, aad)
|
||||
|
||||
assert decrypted == pt
|
||||
assert rik_a == rik_b
|
||||
|
||||
|
||||
def test_first_message_wrong_key():
|
||||
ck = os.urandom(32)
|
||||
ct, _ = soliton.Ratchet.encrypt_first_message(ck, b"hello", b"aad")
|
||||
try:
|
||||
soliton.Ratchet.decrypt_first_message(os.urandom(32), ct, b"aad")
|
||||
assert False, "should have raised AeadError"
|
||||
except soliton.AeadError:
|
||||
pass
|
||||
|
||||
|
||||
def test_first_message_wrong_aad():
|
||||
ck = os.urandom(32)
|
||||
ct, _ = soliton.Ratchet.encrypt_first_message(ck, b"hello", b"aad1")
|
||||
try:
|
||||
soliton.Ratchet.decrypt_first_message(ck, ct, b"aad2")
|
||||
assert False, "should have raised AeadError"
|
||||
except soliton.AeadError:
|
||||
pass
|
||||
|
||||
|
||||
def test_first_message_empty_plaintext():
|
||||
ck = os.urandom(32)
|
||||
ct, rik = soliton.Ratchet.encrypt_first_message(ck, b"", b"aad")
|
||||
pt, rik2 = soliton.Ratchet.decrypt_first_message(ck, ct, b"aad")
|
||||
assert pt == b""
|
||||
assert rik == rik2
|
||||
|
||||
|
||||
def test_kex_sign_verify_bundle():
|
||||
bob = soliton.Identity.generate()
|
||||
spk_pub, spk_sk = soliton.xwing_keygen()
|
||||
|
||||
sig = soliton.kex_sign_prekey(bob.secret_key(), spk_pub)
|
||||
assert len(sig) == 3373
|
||||
|
||||
soliton.kex_verify_bundle(
|
||||
bob.public_key(), bob.public_key(),
|
||||
spk_pub, 1, sig, "lo-crypto-v1",
|
||||
)
|
||||
bob.close()
|
||||
|
||||
|
||||
def test_kex_verify_bundle_wrong_key():
|
||||
bob = soliton.Identity.generate()
|
||||
eve = soliton.Identity.generate()
|
||||
spk_pub, _ = soliton.xwing_keygen()
|
||||
sig = soliton.kex_sign_prekey(bob.secret_key(), spk_pub)
|
||||
|
||||
try:
|
||||
soliton.kex_verify_bundle(
|
||||
bob.public_key(), eve.public_key(),
|
||||
spk_pub, 1, sig, "lo-crypto-v1",
|
||||
)
|
||||
assert False, "should have raised"
|
||||
except soliton.BundleVerificationError:
|
||||
pass
|
||||
bob.close()
|
||||
eve.close()
|
||||
|
||||
|
||||
def _full_kex():
|
||||
"""Run a complete KEX and return everything needed for ratchet init."""
|
||||
alice = soliton.Identity.generate()
|
||||
bob = soliton.Identity.generate()
|
||||
spk_pub, spk_sk = soliton.xwing_keygen()
|
||||
spk_sig = soliton.kex_sign_prekey(bob.secret_key(), spk_pub)
|
||||
|
||||
initiated = soliton.kex_initiate(
|
||||
alice.public_key(), alice.secret_key(),
|
||||
bob.public_key(), spk_pub, 1, spk_sig, "lo-crypto-v1",
|
||||
)
|
||||
|
||||
si_encoded = initiated.session_init_encoded()
|
||||
received = soliton.kex_receive(
|
||||
bob.public_key(), bob.secret_key(), alice.public_key(),
|
||||
si_encoded, initiated.sender_sig(), spk_sk,
|
||||
)
|
||||
|
||||
return alice, bob, initiated, received, si_encoded
|
||||
|
||||
|
||||
def test_full_kex_round_trip():
|
||||
alice, bob, initiated, received, si_encoded = _full_kex()
|
||||
|
||||
# First message.
|
||||
aad = soliton.kex_build_first_message_aad(
|
||||
initiated.sender_fingerprint(),
|
||||
initiated.recipient_fingerprint(),
|
||||
si_encoded,
|
||||
)
|
||||
|
||||
ct, rik_a = soliton.Ratchet.encrypt_first_message(
|
||||
initiated.take_initial_chain_key(), b"hello bob", aad,
|
||||
)
|
||||
pt, rik_b = soliton.Ratchet.decrypt_first_message(
|
||||
received.take_initial_chain_key(), ct, aad,
|
||||
)
|
||||
assert pt == b"hello bob"
|
||||
assert rik_a == rik_b
|
||||
|
||||
# Init ratchets.
|
||||
alice_ratchet = soliton.Ratchet.init_alice(
|
||||
initiated.take_root_key(), rik_a,
|
||||
alice.fingerprint(), bob.fingerprint(),
|
||||
received.peer_ek(), initiated.ek_sk(),
|
||||
)
|
||||
bob_ratchet = soliton.Ratchet.init_bob(
|
||||
received.take_root_key(), rik_b,
|
||||
bob.fingerprint(), alice.fingerprint(),
|
||||
received.peer_ek(),
|
||||
)
|
||||
|
||||
# Alice sends to Bob.
|
||||
hdr, ct = alice_ratchet.encrypt(b"message 1")
|
||||
assert bob_ratchet.decrypt(hdr, ct) == b"message 1"
|
||||
|
||||
# Bob replies (direction change — KEM ratchet step).
|
||||
hdr2, ct2 = bob_ratchet.encrypt(b"reply 1")
|
||||
assert alice_ratchet.decrypt(hdr2, ct2) == b"reply 1"
|
||||
|
||||
# Multiple messages same direction.
|
||||
hdr3, ct3 = alice_ratchet.encrypt(b"message 2")
|
||||
hdr4, ct4 = alice_ratchet.encrypt(b"message 3")
|
||||
assert bob_ratchet.decrypt(hdr3, ct3) == b"message 2"
|
||||
assert bob_ratchet.decrypt(hdr4, ct4) == b"message 3"
|
||||
|
||||
alice_ratchet.close()
|
||||
bob_ratchet.close()
|
||||
initiated.close()
|
||||
received.close()
|
||||
alice.close()
|
||||
bob.close()
|
||||
|
||||
|
||||
def test_ratchet_duplicate_rejected():
|
||||
alice, bob, initiated, received, si_encoded = _full_kex()
|
||||
aad = soliton.kex_build_first_message_aad(
|
||||
initiated.sender_fingerprint(), initiated.recipient_fingerprint(), si_encoded,
|
||||
)
|
||||
ct, rik_a = soliton.Ratchet.encrypt_first_message(initiated.take_initial_chain_key(), b"x", aad)
|
||||
_, rik_b = soliton.Ratchet.decrypt_first_message(received.take_initial_chain_key(), ct, aad)
|
||||
|
||||
alice_r = soliton.Ratchet.init_alice(
|
||||
initiated.take_root_key(), rik_a,
|
||||
alice.fingerprint(), bob.fingerprint(),
|
||||
received.peer_ek(), initiated.ek_sk(),
|
||||
)
|
||||
bob_r = soliton.Ratchet.init_bob(
|
||||
received.take_root_key(), rik_b,
|
||||
bob.fingerprint(), alice.fingerprint(),
|
||||
received.peer_ek(),
|
||||
)
|
||||
|
||||
hdr, ct = alice_r.encrypt(b"unique")
|
||||
assert bob_r.decrypt(hdr, ct) == b"unique"
|
||||
|
||||
# Replay must fail.
|
||||
try:
|
||||
bob_r.decrypt(hdr, ct)
|
||||
assert False, "should have raised DuplicateMessageError"
|
||||
except soliton.DuplicateMessageError:
|
||||
pass
|
||||
|
||||
alice_r.close()
|
||||
bob_r.close()
|
||||
initiated.close()
|
||||
received.close()
|
||||
alice.close()
|
||||
bob.close()
|
||||
|
||||
|
||||
def test_ratchet_serialize_deserialize():
|
||||
alice, bob, initiated, received, si_encoded = _full_kex()
|
||||
aad = soliton.kex_build_first_message_aad(
|
||||
initiated.sender_fingerprint(), initiated.recipient_fingerprint(), si_encoded,
|
||||
)
|
||||
ct, rik_a = soliton.Ratchet.encrypt_first_message(initiated.take_initial_chain_key(), b"x", aad)
|
||||
_, rik_b = soliton.Ratchet.decrypt_first_message(received.take_initial_chain_key(), ct, aad)
|
||||
|
||||
alice_r = soliton.Ratchet.init_alice(
|
||||
initiated.take_root_key(), rik_a,
|
||||
alice.fingerprint(), bob.fingerprint(),
|
||||
received.peer_ek(), initiated.ek_sk(),
|
||||
)
|
||||
|
||||
# Send a message to advance state.
|
||||
hdr, ct = alice_r.encrypt(b"before serialize")
|
||||
blob, epoch = alice_r.to_bytes()
|
||||
assert len(blob) > 0
|
||||
assert epoch >= 1
|
||||
|
||||
# Deserialize.
|
||||
restored = soliton.Ratchet.from_bytes(blob, 0)
|
||||
hdr2, ct2 = restored.encrypt(b"after restore")
|
||||
assert len(ct2) > 0
|
||||
|
||||
restored.close()
|
||||
initiated.close()
|
||||
received.close()
|
||||
alice.close()
|
||||
bob.close()
|
||||
|
||||
|
||||
def test_derive_call_keys():
|
||||
alice, bob, initiated, received, si_encoded = _full_kex()
|
||||
aad = soliton.kex_build_first_message_aad(
|
||||
initiated.sender_fingerprint(), initiated.recipient_fingerprint(), si_encoded,
|
||||
)
|
||||
ct, rik_a = soliton.Ratchet.encrypt_first_message(initiated.take_initial_chain_key(), b"x", aad)
|
||||
_, rik_b = soliton.Ratchet.decrypt_first_message(received.take_initial_chain_key(), ct, aad)
|
||||
|
||||
alice_r = soliton.Ratchet.init_alice(
|
||||
initiated.take_root_key(), rik_a,
|
||||
alice.fingerprint(), bob.fingerprint(),
|
||||
received.peer_ek(), initiated.ek_sk(),
|
||||
)
|
||||
|
||||
kem_ss = os.urandom(32)
|
||||
call_id = os.urandom(16)
|
||||
|
||||
with alice_r.derive_call_keys(kem_ss, call_id) as keys:
|
||||
send = keys.send_key()
|
||||
recv = keys.recv_key()
|
||||
assert len(send) == 32
|
||||
assert len(recv) == 32
|
||||
assert send != recv
|
||||
keys.advance()
|
||||
send2 = keys.send_key()
|
||||
assert send2 != send # keys changed after advance
|
||||
|
||||
alice_r.close()
|
||||
initiated.close()
|
||||
received.close()
|
||||
alice.close()
|
||||
bob.close()
|
||||
|
||||
|
||||
def test_ratchet_can_serialize_and_epoch():
|
||||
alice, bob, initiated, received, si_encoded = _full_kex()
|
||||
aad = soliton.kex_build_first_message_aad(
|
||||
initiated.sender_fingerprint(), initiated.recipient_fingerprint(), si_encoded,
|
||||
)
|
||||
ct, rik_a = soliton.Ratchet.encrypt_first_message(initiated.take_initial_chain_key(), b"x", aad)
|
||||
_, rik_b = soliton.Ratchet.decrypt_first_message(received.take_initial_chain_key(), ct, aad)
|
||||
|
||||
alice_r = soliton.Ratchet.init_alice(
|
||||
initiated.take_root_key(), rik_a,
|
||||
alice.fingerprint(), bob.fingerprint(),
|
||||
initiated.ek_pk(), initiated.ek_sk(),
|
||||
)
|
||||
|
||||
assert alice_r.can_serialize()
|
||||
assert alice_r.epoch() == 0
|
||||
|
||||
alice_r.encrypt(b"advance")
|
||||
assert alice_r.epoch() == 0 # same-direction doesn't change epoch
|
||||
assert alice_r.can_serialize()
|
||||
|
||||
alice_r.close()
|
||||
initiated.close()
|
||||
received.close()
|
||||
alice.close()
|
||||
bob.close()
|
||||
|
||||
|
||||
def test_ratchet_reset():
|
||||
alice, bob, initiated, received, si_encoded = _full_kex()
|
||||
aad = soliton.kex_build_first_message_aad(
|
||||
initiated.sender_fingerprint(), initiated.recipient_fingerprint(), si_encoded,
|
||||
)
|
||||
ct, rik_a = soliton.Ratchet.encrypt_first_message(initiated.take_initial_chain_key(), b"x", aad)
|
||||
_, _ = soliton.Ratchet.decrypt_first_message(received.take_initial_chain_key(), ct, aad)
|
||||
|
||||
alice_r = soliton.Ratchet.init_alice(
|
||||
initiated.take_root_key(), rik_a,
|
||||
alice.fingerprint(), bob.fingerprint(),
|
||||
initiated.ek_pk(), initiated.ek_sk(),
|
||||
)
|
||||
|
||||
alice_r.encrypt(b"before reset")
|
||||
alice_r.reset()
|
||||
|
||||
# Encrypt after reset should fail.
|
||||
try:
|
||||
alice_r.encrypt(b"after reset")
|
||||
assert False, "should have raised"
|
||||
except soliton.InvalidDataError:
|
||||
pass
|
||||
|
||||
alice_r.close()
|
||||
initiated.close()
|
||||
received.close()
|
||||
alice.close()
|
||||
bob.close()
|
||||
|
||||
|
||||
def test_verification_phrase_symmetric():
|
||||
alice = soliton.Identity.generate()
|
||||
bob = soliton.Identity.generate()
|
||||
|
||||
phrase1 = soliton.verification_phrase(alice.public_key(), bob.public_key())
|
||||
phrase2 = soliton.verification_phrase(bob.public_key(), alice.public_key())
|
||||
|
||||
assert len(phrase1) > 0
|
||||
assert phrase1 == phrase2
|
||||
|
||||
alice.close()
|
||||
bob.close()
|
||||
55
soliton_py/tests/test_primitives.py
Normal file
55
soliton_py/tests/test_primitives.py
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
"""Tests for primitive cryptographic operations."""
|
||||
|
||||
import soliton
|
||||
|
||||
|
||||
def test_sha3_256_known_vector():
|
||||
"""FIPS 202 test vector: SHA3-256("abc")."""
|
||||
result = soliton.sha3_256(b"abc")
|
||||
expected = bytes.fromhex(
|
||||
"3a985da74fe225b2045c172d6bd390bd"
|
||||
"855f086e3e9d525b46bfe24511431532"
|
||||
)
|
||||
assert result == expected
|
||||
|
||||
|
||||
def test_sha3_256_empty():
|
||||
"""FIPS 202 test vector: SHA3-256("")."""
|
||||
result = soliton.sha3_256(b"")
|
||||
expected = bytes.fromhex(
|
||||
"a7ffc6f8bf1ed76651c14756a061d662"
|
||||
"f580ff4de43b49fa82d80a4b80f8434a"
|
||||
)
|
||||
assert result == expected
|
||||
|
||||
|
||||
def test_fingerprint_hex():
|
||||
result = soliton.fingerprint_hex(b"abc")
|
||||
assert isinstance(result, str)
|
||||
assert len(result) == 64 # 32 bytes hex-encoded
|
||||
|
||||
|
||||
def test_hmac_sha3_256():
|
||||
key = b"\x0b" * 32
|
||||
data = b"Hi There"
|
||||
tag = soliton.hmac_sha3_256(key, data)
|
||||
assert len(tag) == 32
|
||||
|
||||
|
||||
def test_hmac_sha3_256_verify():
|
||||
key = b"\x0b" * 32
|
||||
data = b"Hi There"
|
||||
tag = soliton.hmac_sha3_256(key, data)
|
||||
assert soliton.hmac_sha3_256_verify(tag, tag) is True
|
||||
# Tampered tag should fail.
|
||||
tampered = bytearray(tag)
|
||||
tampered[0] ^= 0xFF
|
||||
assert soliton.hmac_sha3_256_verify(tag, bytes(tampered)) is False
|
||||
|
||||
|
||||
def test_hkdf_sha3_256():
|
||||
salt = b"\x00" * 32
|
||||
ikm = b"\x0b" * 32
|
||||
info = b"test"
|
||||
okm = soliton.hkdf_sha3_256(salt, ikm, info, length=64)
|
||||
assert len(okm) == 64
|
||||
102
soliton_py/tests/test_storage.py
Normal file
102
soliton_py/tests/test_storage.py
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
"""Tests for encrypted storage."""
|
||||
|
||||
import os
|
||||
import soliton
|
||||
|
||||
|
||||
def _random_key():
|
||||
return os.urandom(32)
|
||||
|
||||
|
||||
def test_storage_round_trip():
|
||||
with soliton.StorageKeyRing(1, _random_key()) as ring:
|
||||
pt = b"encrypted storage data"
|
||||
blob = ring.encrypt_blob("channel-1", "segment-0", pt)
|
||||
result = ring.decrypt_blob("channel-1", "segment-0", blob)
|
||||
assert result == pt
|
||||
|
||||
|
||||
def test_storage_wrong_channel_fails():
|
||||
with soliton.StorageKeyRing(1, _random_key()) as ring:
|
||||
blob = ring.encrypt_blob("channel-1", "seg", b"data")
|
||||
try:
|
||||
ring.decrypt_blob("channel-2", "seg", blob)
|
||||
assert False, "should have raised AeadError"
|
||||
except soliton.AeadError:
|
||||
pass
|
||||
|
||||
|
||||
def test_storage_wrong_segment_fails():
|
||||
with soliton.StorageKeyRing(1, _random_key()) as ring:
|
||||
blob = ring.encrypt_blob("ch", "seg-1", b"data")
|
||||
try:
|
||||
ring.decrypt_blob("ch", "seg-2", blob)
|
||||
assert False, "should have raised AeadError"
|
||||
except soliton.AeadError:
|
||||
pass
|
||||
|
||||
|
||||
def test_storage_key_rotation():
|
||||
key1 = _random_key()
|
||||
key2 = _random_key()
|
||||
with soliton.StorageKeyRing(1, key1) as ring:
|
||||
blob_v1 = ring.encrypt_blob("ch", "seg", b"v1 data")
|
||||
ring.add_key(2, key2, make_active=True)
|
||||
blob_v2 = ring.encrypt_blob("ch", "seg", b"v2 data")
|
||||
# Both decrypt (both keys in ring).
|
||||
assert ring.decrypt_blob("ch", "seg", blob_v1) == b"v1 data"
|
||||
assert ring.decrypt_blob("ch", "seg", blob_v2) == b"v2 data"
|
||||
|
||||
|
||||
def test_dm_queue_round_trip():
|
||||
fp = os.urandom(32)
|
||||
with soliton.StorageKeyRing(1, _random_key()) as ring:
|
||||
pt = b"queued DM"
|
||||
blob = ring.encrypt_dm_queue(fp, "batch-1", pt)
|
||||
result = ring.decrypt_dm_queue(fp, "batch-1", blob)
|
||||
assert result == pt
|
||||
|
||||
|
||||
def test_dm_queue_wrong_fingerprint_fails():
|
||||
fp1 = os.urandom(32)
|
||||
fp2 = os.urandom(32)
|
||||
with soliton.StorageKeyRing(1, _random_key()) as ring:
|
||||
blob = ring.encrypt_dm_queue(fp1, "batch", b"msg")
|
||||
try:
|
||||
ring.decrypt_dm_queue(fp2, "batch", blob)
|
||||
assert False, "should have raised AeadError"
|
||||
except soliton.AeadError:
|
||||
pass
|
||||
|
||||
|
||||
def test_storage_empty_plaintext():
|
||||
with soliton.StorageKeyRing(1, _random_key()) as ring:
|
||||
blob = ring.encrypt_blob("ch", "seg", b"")
|
||||
assert ring.decrypt_blob("ch", "seg", blob) == b""
|
||||
|
||||
|
||||
def test_storage_compress():
|
||||
with soliton.StorageKeyRing(1, _random_key()) as ring:
|
||||
data = b"compressible " * 100
|
||||
blob = ring.encrypt_blob("ch", "seg", data, compress=True)
|
||||
assert ring.decrypt_blob("ch", "seg", blob) == data
|
||||
|
||||
|
||||
def test_remove_key():
|
||||
with soliton.StorageKeyRing(1, _random_key()) as ring:
|
||||
ring.add_key(2, _random_key(), make_active=True)
|
||||
ring.remove_key(1)
|
||||
blob = ring.encrypt_blob("ch", "seg", b"after remove")
|
||||
assert ring.decrypt_blob("ch", "seg", blob) == b"after remove"
|
||||
|
||||
|
||||
def test_context_manager():
|
||||
ring = soliton.StorageKeyRing(1, _random_key())
|
||||
with ring:
|
||||
ring.encrypt_blob("ch", "seg", b"test")
|
||||
# After exit, operations should fail.
|
||||
try:
|
||||
ring.encrypt_blob("ch", "seg", b"test")
|
||||
assert False, "should have raised"
|
||||
except soliton.InvalidDataError:
|
||||
pass
|
||||
161
soliton_py/tests/test_stream.py
Normal file
161
soliton_py/tests/test_stream.py
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
"""Tests for streaming AEAD."""
|
||||
|
||||
import os
|
||||
import soliton
|
||||
|
||||
|
||||
CHUNK_SIZE = 1_048_576 # 1 MiB
|
||||
|
||||
|
||||
def _random_key():
|
||||
return os.urandom(32)
|
||||
|
||||
|
||||
def test_stream_single_chunk():
|
||||
key = _random_key()
|
||||
with soliton.StreamEncryptor(key) as enc:
|
||||
header = enc.header()
|
||||
assert len(header) == 26
|
||||
ct = enc.encrypt_chunk(b"hello stream", is_last=True)
|
||||
assert enc.is_finalized()
|
||||
|
||||
with soliton.StreamDecryptor(key, header) as dec:
|
||||
pt, is_last = dec.decrypt_chunk(ct)
|
||||
assert pt == b"hello stream"
|
||||
assert is_last
|
||||
|
||||
|
||||
def test_stream_multi_chunk():
|
||||
key = _random_key()
|
||||
chunk1_data = os.urandom(CHUNK_SIZE) # non-final must be 1 MiB
|
||||
chunk2_data = b"final chunk"
|
||||
|
||||
with soliton.StreamEncryptor(key) as enc:
|
||||
header = enc.header()
|
||||
ct1 = enc.encrypt_chunk(chunk1_data, is_last=False)
|
||||
ct2 = enc.encrypt_chunk(chunk2_data, is_last=True)
|
||||
|
||||
with soliton.StreamDecryptor(key, header) as dec:
|
||||
pt1, last1 = dec.decrypt_chunk(ct1)
|
||||
assert pt1 == chunk1_data
|
||||
assert not last1
|
||||
|
||||
pt2, last2 = dec.decrypt_chunk(ct2)
|
||||
assert pt2 == chunk2_data
|
||||
assert last2
|
||||
|
||||
|
||||
def test_stream_with_aad():
|
||||
key = _random_key()
|
||||
aad = b"file-id:12345"
|
||||
|
||||
with soliton.StreamEncryptor(key, aad=aad) as enc:
|
||||
header = enc.header()
|
||||
ct = enc.encrypt_chunk(b"aad-bound data", is_last=True)
|
||||
|
||||
# Correct AAD decrypts.
|
||||
with soliton.StreamDecryptor(key, header, aad=aad) as dec:
|
||||
pt, _ = dec.decrypt_chunk(ct)
|
||||
assert pt == b"aad-bound data"
|
||||
|
||||
# Wrong AAD fails.
|
||||
try:
|
||||
with soliton.StreamDecryptor(key, header, aad=b"wrong") as dec:
|
||||
dec.decrypt_chunk(ct)
|
||||
assert False, "should have raised"
|
||||
except soliton.AeadError:
|
||||
pass
|
||||
|
||||
|
||||
def test_stream_wrong_key_fails():
|
||||
key1 = _random_key()
|
||||
key2 = _random_key()
|
||||
with soliton.StreamEncryptor(key1) as enc:
|
||||
header = enc.header()
|
||||
ct = enc.encrypt_chunk(b"data", is_last=True)
|
||||
|
||||
try:
|
||||
with soliton.StreamDecryptor(key2, header) as dec:
|
||||
dec.decrypt_chunk(ct)
|
||||
assert False, "should have raised"
|
||||
except soliton.AeadError:
|
||||
pass
|
||||
|
||||
|
||||
def test_stream_tampered_ciphertext():
|
||||
key = _random_key()
|
||||
with soliton.StreamEncryptor(key) as enc:
|
||||
header = enc.header()
|
||||
ct = bytearray(enc.encrypt_chunk(b"data", is_last=True))
|
||||
ct[0] ^= 0xFF
|
||||
|
||||
try:
|
||||
with soliton.StreamDecryptor(key, header) as dec:
|
||||
dec.decrypt_chunk(bytes(ct))
|
||||
assert False, "should have raised"
|
||||
except (soliton.AeadError, soliton.InvalidDataError):
|
||||
pass
|
||||
|
||||
|
||||
def test_stream_empty_plaintext():
|
||||
key = _random_key()
|
||||
with soliton.StreamEncryptor(key) as enc:
|
||||
header = enc.header()
|
||||
ct = enc.encrypt_chunk(b"", is_last=True)
|
||||
|
||||
with soliton.StreamDecryptor(key, header) as dec:
|
||||
pt, is_last = dec.decrypt_chunk(ct)
|
||||
assert pt == b""
|
||||
assert is_last
|
||||
|
||||
|
||||
def test_stream_encrypt_at_decrypt_at():
|
||||
key = _random_key()
|
||||
with soliton.StreamEncryptor(key) as enc:
|
||||
header = enc.header()
|
||||
# Short plaintext requires is_last=True (non-final must be exactly 1 MiB).
|
||||
ct0 = enc.encrypt_chunk_at(0, b"at index zero", is_last=True)
|
||||
|
||||
with soliton.StreamDecryptor(key, header) as dec:
|
||||
pt0, last0 = dec.decrypt_chunk_at(0, ct0)
|
||||
assert pt0 == b"at index zero"
|
||||
assert last0
|
||||
|
||||
|
||||
def test_stream_decrypt_at_different_indices():
|
||||
key = _random_key()
|
||||
with soliton.StreamEncryptor(key) as enc:
|
||||
header = enc.header()
|
||||
ct5 = enc.encrypt_chunk_at(5, b"at five", is_last=True)
|
||||
ct99 = enc.encrypt_chunk_at(99, b"at ninety-nine", is_last=True)
|
||||
|
||||
# Decrypt in reverse order.
|
||||
with soliton.StreamDecryptor(key, header) as dec:
|
||||
pt99, _ = dec.decrypt_chunk_at(99, ct99)
|
||||
assert pt99 == b"at ninety-nine"
|
||||
|
||||
pt5, _ = dec.decrypt_chunk_at(5, ct5)
|
||||
assert pt5 == b"at five"
|
||||
|
||||
|
||||
def test_stream_expected_index():
|
||||
key = _random_key()
|
||||
with soliton.StreamEncryptor(key) as enc:
|
||||
header = enc.header()
|
||||
ct = enc.encrypt_chunk(b"chunk", is_last=True)
|
||||
|
||||
with soliton.StreamDecryptor(key, header) as dec:
|
||||
assert dec.expected_index() == 0
|
||||
dec.decrypt_chunk(ct)
|
||||
assert dec.expected_index() == 1
|
||||
|
||||
|
||||
def test_stream_context_manager():
|
||||
enc = soliton.StreamEncryptor(_random_key())
|
||||
with enc:
|
||||
enc.header()
|
||||
try:
|
||||
enc.header()
|
||||
assert False, "should have raised"
|
||||
except soliton.InvalidDataError:
|
||||
pass
|
||||
Loading…
Add table
Add a link
Reference in a new issue