This commit is contained in:
2025-07-25 23:24:13 +08:00
parent e34bcd80dd
commit 4f366c12a3
84 changed files with 12608 additions and 2 deletions

3
.gitmodules vendored Normal file
View File

@@ -0,0 +1,3 @@
[submodule "hw-sign-win/TSS.MSR"]
path = hw-sign-win/TSS.MSR
url = https://github.com/reitowo/TSS.MSR.git

674
LICENSE Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 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 General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is 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. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
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.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
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 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. Use with the GNU Affero General Public License.
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 Affero 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 special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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 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 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 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 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 General Public License for more details.
You should have received a copy of the GNU 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 the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
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 GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

191
README.md
View File

@@ -1,3 +1,190 @@
# hw-sign
# Hardware-Bound Authentication System
Colon from: https://github.com/reitowo/hw-sign
Minimum Prototype Verification
## Overview
Binding login sessions to a pair of asymmetric keys in the device's hardware security module that cannot be exported, fundamentally preventing token theft or unauthorized use on other devices.
## Design
### Hardware Key Binding
- Hardware security module directly generates key pairs, private key cannot be exported
- Each request is verified through signatures
### Fallback Mechanism
Hardware binding is preferred, but when hardware security is unavailable, the system will degrade:
- Windows: System version too old, TPM doesn't exist or is disabled in BIOS
- Android: System version too old, neither TEE nor StrongBox exists
In these cases, login state is not protected by hardware keys, but normal usage is not affected
### Decoupled Process
- Agnostic to login state implementation, such as Cookies or various application Token systems
- Separated from login flow, which can use more secure authentication like WebAuthn
## Technical Implementation
### Key Architecture
#### Hardware Keys (Device Binding)
- Non-extractable cryptographic key pairs stored in hardware
- New key generated for each login session
- Dedicated to signing temporary keys
- Associated with login state, not user accounts
#### Temporary Keys (Memory-Only)
- Cryptographic key pairs stored only in memory to improve performance
- Signed by hardware keys to verify authenticity
- Used for regular API request signatures or ECDH key negotiation
- Supports rotation and regeneration (app restart/session expiry)
### Algorithm Priority and Format Requirements
#### Hardware Key Type Priority
1. ED25519
2. ECDSA (P-256) (secp256r1) - identified as `ecdsa-p256`
3. RSA-PSS (2048) - identified as `rsa-2048`
#### Temporary Key Type Priority
1. ECDH (P-256) - identified as `ecdh-p256` (for key negotiation)
2. ECDSA (P-256) - identified as `ecdsa-p256`
3. RSA-PSS (2048) - identified as `rsa-2048`
### Platform-Specific Implementation
#### Browser (Web Crypto API)
- Uses SubtleCrypto API
- IndexedDB-based key reference storage (non-exportable)
Example implementation: `hw-sign-browser/src/services/authService.ts`
#### Windows (CNG/NCrypt)
- Uses Windows CryptoNG (NCrypt) API
- TPM-based key storage
Example implementation: `hw-sign-win/main.cpp`
#### Apple (Secure Enclave)
- Uses SecKey API
- Secure Enclave-based key storage
Example implementation: `hw-sign-apple/hw-sign-apple/Services/AuthService.swift`
#### Android (Keystore)
- Uses Android Keystore API
- TEE / StrongBox-based key storage
Example implementation: `hw-sign-android/app/src/main/java/fan/ovo/hwsign/AuthService.kt`
### Example API Protocol Specification
#### Authentication Flow
1. Registration (POST /register)
- Standard user registration, without hardware binding
```json
{
"username": "string",
"password": "string"
}
```
2. Hardware-Bound Login (POST /login)
- Request Headers:
- `x-rpc-sec-bound-token-hw-pub`: Hardware public key (base64 encoded)
- `x-rpc-sec-bound-token-hw-pub-type`: Key algorithm ("ecdsa-p256", "rsa-2048")
- Request Body:
```json
{
"username": "string",
"password": "string"
}
```
- Response:
```json
{
"token": "string"
}
```
3. Authenticated API Request (GET /authenticated)
Common Request Headers:
- `Authorization: Bearer <token>`
- `x-rpc-sec-bound-token-data`: Timestamp+RandomHex string
- `x-rpc-sec-bound-token-data-sig`: Request signature
For New Temporary Keys:
- `x-rpc-sec-bound-token-accel-pub`: Temporary public key
- `x-rpc-sec-bound-token-accel-pub-type`: Key algorithm type
- `x-rpc-sec-bound-token-accel-pub-sig`: Hardware-signed temporary key
New Temporary Key Response Headers:
- `x-rpc-sec-bound-token-accel-pub-id`: Temporary key ID
- `x-rpc-sec-bound-token-accel-pub-expire`: Expiration as Unix timestamp in seconds
For Existing Keys:
- `x-rpc-sec-bound-token-accel-pub-id`: Temporary key ID
### Request Signatures
Format for `x-rpc-sec-bound-token-data` is `{Timestamp}-{32BytesRandomHex}`, ordered by security from high to low:
1. Random String with Redis
- Signs random nonce
- Stored in Redis to prevent replay attacks
- Best security, requires Redis
- Server uses each value only once, repeated use considered invalid
- Server rejects requests where Timestamp < Now - TExpire
2. Request Body Hash
- Signs SHA256 hash of request body
- No additional storage needed
- Requires access to original request body (may not apply to gRPC interfaces)
3. Timestamp
- Signs current timestamp
- Sets short expiration window
- Simplest, slightly lower security
### Performance Optimization - ECDH Key Negotiation
For performance-sensitive scenarios, ECDH-negotiated shared keys with HMAC-SHA256 for high-performance signatures:
1. Initialization Process:
- SDK generates temporary key pair (CliTmpPub/CliTmpPriv) during initialization
- Hardware private key signs CliTmpPub (only once)
- No need for hardware signing again during this program execution
2. Request Signature Process:
- On first request, server generates temporary key pair (SrvTmpPub/SrvTmpPriv)
- Server uses CliTmpPub+SrvTmpPriv to generate shared key HmacSecret via ECDH
- Client uses SrvTmpPub+CliTmpPriv to generate the same HmacSecret via ECDH
- Subsequent requests use HmacSecret to calculate HMAC-SHA256 signatures for better performance
#### Reference Parameters
When generating new temporary negotiation key pairs:
- `x-rpc-sec-bound-token-accel-pub`: Client temporary negotiation public key
- `x-rpc-sec-bound-token-accel-pub-type`: Client temporary negotiation public key type: `ecdh-p256`
- `x-rpc-sec-bound-token-accel-pub-sig`: Signature of client temporary negotiation public key generated with hardware key
When server returns new temporary negotiation public key:
- `x-rpc-sec-bound-token-accel-pub`: Server temporary negotiation public key
- `x-rpc-sec-bound-token-accel-pub-id`: Temporary negotiation public key ID, pointing to the negotiated symmetric key
- `x-rpc-sec-bound-token-accel-pub-expire`: Expiration Unix timestamp in seconds
Signature parameters in requests:
- `x-rpc-sec-bound-token-data`: Format is `{Timestamp}-{32BytesRandomHex}`
- `x-rpc-sec-bound-token-data-sig`: HMAC calculated with negotiated symmetric key on the above data
- `x-rpc-sec-bound-token-accel-pub-id`: Temporary public key ID
## Examples
All subfolders correspond to example implementations for each platform and can be directly opened as projects for compilation
## Compare to DBSC (Device Bound Session Credentials)
DBSC is also a cool solution with similar ideas. However, it is designed for Web Platform, and this repo use native abilities for all platforms. DBSC also doesn't sign all requests with hardware crypto keypairs, while this one will sign all requests.
> Note: Over 90% of the code was generated with AI assistance, but human verification ensures correctness

3
hw-sign-android/.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
.gradle/
.kotlin/
local.properties

1
hw-sign-android/app/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/build

View File

@@ -0,0 +1,61 @@
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.compose)
}
android {
namespace = "fan.ovo.hwsign"
compileSdk = 35
defaultConfig {
applicationId = "fan.ovo.hwsign"
minSdk = 29
targetSdk = 35
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
kotlinOptions {
jvmTarget = "11"
}
buildFeatures {
compose = true
}
}
dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.activity.compose)
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.ui)
implementation(libs.androidx.ui.graphics)
implementation(libs.androidx.ui.tooling.preview)
implementation(libs.androidx.material3)
implementation("androidx.security:security-crypto:1.1.0-alpha06")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4")
implementation("com.squareup.okhttp3:okhttp:4.12.0")
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
androidTestImplementation(platform(libs.androidx.compose.bom))
androidTestImplementation(libs.androidx.ui.test.junit4)
debugImplementation(libs.androidx.ui.tooling)
debugImplementation(libs.androidx.ui.test.manifest)
}

21
hw-sign-android/app/proguard-rules.pro vendored Normal file
View File

@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View File

@@ -0,0 +1,24 @@
package fan.ovo.hwsign
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("fan.ovo.hwsign", appContext.packageName)
}
}

View File

@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="fan.ovo.hwsign">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Dbcs"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.Dbcs">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@@ -0,0 +1,212 @@
package fan.ovo.hwsign
import android.content.Context
import androidx.core.content.edit
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.IOException
import java.util.Base64
import java.util.concurrent.TimeUnit
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
class AuthService(private val context: Context) {
// Constants
private val baseUrl = "https://dbcs-api.ovo.fan"
private val jsonContentType = "application/json; charset=utf-8".toMediaType()
private val keyAuthToken = "auth_token"
// Key management
public val keyManager = KeyManager(context)
// Lazy initialization for network client
private val client by lazy {
OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()
}
private val sharedPreferences by lazy {
EncryptedSharedPreferences.create(
context,
"auth_prefs",
MasterKey.Builder(context)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build(),
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
}
/**
* Store and retrieve auth token from encrypted preferences
*/
private fun storeAuthToken(token: String) =
sharedPreferences.edit { putString(keyAuthToken, token) }
private fun getAuthToken(): String? =
sharedPreferences.getString(keyAuthToken, null)
/**
* Register a new user
*/
suspend fun register(username: String, password: String): Boolean =
withContext(Dispatchers.IO) {
try {
val json = JSONObject().apply {
put("username", username)
put("password", password)
}
val requestBody = json.toString().toRequestBody(jsonContentType)
val request = Request.Builder()
.url("$baseUrl/register")
.post(requestBody)
.build()
val response = client.newCall(request).await()
if (response.isSuccessful) {
response.body?.string()?.let { body ->
val jsonResponse = JSONObject(body)
return@withContext jsonResponse.optString("message", "").isNotEmpty()
}
}
false
} catch (e: Exception) {
e.printStackTrace()
false
}
}
/**
* Login using username/password and register hardware key
*/
suspend fun login(username: String, password: String): Boolean =
withContext(Dispatchers.IO) {
try {
// Generate new hardware key
val keyPair = keyManager.generateHardwareKey()
val publicKey = Base64.getEncoder().encodeToString(keyPair.public.encoded)
val json = JSONObject().apply {
put("username", username)
put("password", password)
}
val requestBody = json.toString().toRequestBody(jsonContentType)
val request = Request.Builder()
.url("$baseUrl/login")
.header("x-rpc-sec-bound-token-hw-pub", publicKey)
.header("x-rpc-sec-bound-token-hw-pub-type", "ecdsa")
.post(requestBody)
.build()
val response = client.newCall(request).await()
if (response.isSuccessful) {
response.body?.string()?.let { body ->
val jsonResponse = JSONObject(body)
val token = jsonResponse.optString("token", "")
if (token.isNotEmpty()) {
storeAuthToken(token)
// Clear any existing acceleration resources
keyManager.clearAccelKeyId()
return@withContext true
}
}
}
false
} catch (e: Exception) {
e.printStackTrace()
false
}
}
/**
* Check authentication status and manage acceleration keys
*/
suspend fun checkAuthentication(): Boolean = withContext(Dispatchers.IO) {
val token = getAuthToken() ?: return@withContext false
val timestamp = System.currentTimeMillis().toString()
try {
val accelKeyId = keyManager.getAccelKeyId()
val requestBuilder = Request.Builder()
.url("$baseUrl/authenticated")
.header("Authorization", "Bearer $token")
.header("x-rpc-sec-bound-token-data", timestamp)
if (accelKeyId != null) {
// Use existing acceleration key
val keyPair = keyManager.getOrCreateAccelerationKey()
val signature = keyManager.signWithKey(keyPair, timestamp)
requestBuilder
.header("x-rpc-sec-bound-token-data-sig", signature)
.header("x-rpc-sec-bound-token-accel-pub-id", accelKeyId)
} else {
// Generate a new acceleration key
val keyPair = keyManager.generateAccelerationKey()
val accelPubKey = Base64.getEncoder().encodeToString(keyPair.public.encoded)
val accelPubKeySig = keyManager.signWithHardwareKey(accelPubKey)
val signature = keyManager.signWithKey(keyPair, timestamp)
requestBuilder
.header("x-rpc-sec-bound-token-accel-pub", accelPubKey)
.header("x-rpc-sec-bound-token-accel-pub-type", "ecdsa")
.header("x-rpc-sec-bound-token-accel-pub-sig", accelPubKeySig)
.header("x-rpc-sec-bound-token-data-sig", signature)
}
val request = requestBuilder.get().build()
val response = client.newCall(request).await()
if (response.isSuccessful) {
// Save acceleration key ID if this was a new key registration
response.header("x-rpc-sec-bound-token-accel-pub-id")?.let { newId ->
keyManager.storeAccelKeyId(newId)
}
return@withContext true
}
false
} catch (e: Exception) {
e.printStackTrace()
false
}
}
/**
* Clear all stored credentials and keys
*/
fun logout() {
sharedPreferences.edit {
remove(keyAuthToken)
}
keyManager.clearKeys()
}
/**
* Extension function to simplify OkHttp async calls
*/
private suspend fun Call.await(): Response = suspendCoroutine { continuation ->
this.enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
continuation.resume(response)
}
override fun onFailure(call: Call, e: IOException) {
continuation.resumeWithException(e)
}
})
}
}

View File

@@ -0,0 +1,214 @@
package fan.ovo.hwsign
import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.security.keystore.KeyInfo
import android.util.Log
import androidx.core.content.edit
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.security.KeyFactory
import java.security.KeyPair
import java.security.KeyPairGenerator
import java.security.KeyStore
import java.security.PrivateKey
import java.security.Signature
import java.security.spec.ECGenParameterSpec
import java.util.Base64
/**
* Manages cryptographic keys for hardware-backed authentication
*/
class KeyManager(private val context: Context) {
// Constants
private val keyAlias = "hw_sign_hardware_key"
private val keyAccelId = "accel_key_id"
// Cache for acceleration keys
private var accelerationKeyPair: KeyPair? = null
private val keystore by lazy {
KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
}
private val sharedPreferences by lazy {
EncryptedSharedPreferences.create(
context,
"auth_prefs",
MasterKey.Builder(context)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build(),
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
}
/**
* Check the security level of the hardware key
*/
@SuppressLint("SwitchIntDef")
fun getKeySecurityLevel(): String {
return try {
val privateKey = keystore.getKey(keyAlias, null) as PrivateKey
val keyFactory = KeyFactory.getInstance(privateKey.algorithm, "AndroidKeyStore")
val keyInfo = keyFactory.getKeySpec(privateKey, KeyInfo::class.java) as KeyInfo
// Acceptable value: StrongBox, TEE, SecureHardware.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
when (keyInfo.securityLevel) {
KeyProperties.SECURITY_LEVEL_STRONGBOX -> "StrongBox"
KeyProperties.SECURITY_LEVEL_TRUSTED_ENVIRONMENT -> "TEE"
KeyProperties.SECURITY_LEVEL_UNKNOWN_SECURE -> "UnknownSecure"
KeyProperties.SECURITY_LEVEL_SOFTWARE -> "Software"
KeyProperties.SECURITY_LEVEL_UNKNOWN -> "Unknown"
else -> "Unknown"
}
} else {
if (keyInfo.isInsideSecureHardware) {
"SecureHardware"
} else {
"Insecure"
}
}
} catch (e: Exception) {
e.printStackTrace()
"Unknown"
}
}
/**
* Generate a hardware-backed key pair using AndroidKeyStore
* Attempts to use StrongBox if available, falls back to TEE
*/
suspend fun generateHardwareKey(): KeyPair = withContext(Dispatchers.IO) {
// Delete any existing key
if (keystore.containsAlias(keyAlias)) {
keystore.deleteEntry(keyAlias)
}
val keyPairGenerator = KeyPairGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore"
)
val builder = KeyGenParameterSpec.Builder(
keyAlias, KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY
).apply {
setDigests(KeyProperties.DIGEST_SHA256)
setUserAuthenticationRequired(false)
setUnlockedDeviceRequired(true)
}
var keyPair: KeyPair
// First try StrongBox if available (API 28+)
try {
builder.setIsStrongBoxBacked(true)
keyPairGenerator.initialize(builder.build())
keyPair = keyPairGenerator.generateKeyPair()
} catch (e: Exception) {
// Initialize with TEE fallback
builder.setIsStrongBoxBacked(false)
keyPairGenerator.initialize(builder.build())
keyPair = keyPairGenerator.generateKeyPair()
}
val keyLevel = getKeySecurityLevel()
Log.i(null, "successfully generated key pair in $keyLevel")
keyPair
}
/**
* Retrieve the existing hardware key pair from the Android KeyStore
*/
private fun getHardwareKeyPair(): KeyPair? = try {
if (keystore.containsAlias(keyAlias)) {
val privateKey = keystore.getKey(keyAlias, null) as PrivateKey
val publicKey = keystore.getCertificate(keyAlias).publicKey
KeyPair(publicKey, privateKey)
} else {
null
}
} catch (e: Exception) {
e.printStackTrace()
null
}
/**
* Store and retrieve acceleration key ID
*/
fun storeAccelKeyId(keyId: String) {
sharedPreferences.edit { putString(keyAccelId, keyId) }
}
fun getAccelKeyId(): String? =
sharedPreferences.getString(keyAccelId, null)
fun clearAccelKeyId() {
sharedPreferences.edit { remove(keyAccelId) }
}
/**
* Sign data using the hardware key
*/
suspend fun signWithHardwareKey(data: String): String = withContext(Dispatchers.IO) {
val keyPair = getHardwareKeyPair() ?: throw SecurityException("Hardware key not found")
val signature = Signature.getInstance("SHA256withECDSA").apply {
initSign(keyPair.private)
update(data.toByteArray())
}
Base64.getEncoder().encodeToString(signature.sign())
}
/**
* Generate an acceleration key pair in memory
*/
fun generateAccelerationKey(): KeyPair {
val keyPair = KeyPairGenerator.getInstance("EC").apply {
initialize(ECGenParameterSpec("secp256r1"))
}.generateKeyPair()
accelerationKeyPair = keyPair
return keyPair
}
/**
* Get the cached acceleration key pair or generate a new one
*/
fun getOrCreateAccelerationKey(): KeyPair {
return accelerationKeyPair ?: generateAccelerationKey()
}
/**
* Sign data with a specific key pair
*/
fun signWithKey(keyPair: KeyPair, data: String): String {
val signature = Signature.getInstance("SHA256withECDSA").apply {
initSign(keyPair.private)
update(data.toByteArray())
}
return Base64.getEncoder().encodeToString(signature.sign())
}
/**
* Clear stored keys and identifiers
*/
fun clearKeys() {
accelerationKeyPair = null
clearAccelKeyId()
try {
if (keystore.containsAlias(keyAlias)) {
keystore.deleteEntry(keyAlias)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}

View File

@@ -0,0 +1,115 @@
package fan.ovo.hwsign
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import fan.ovo.hwsign.ui.theme.DbcsTheme
class MainActivity : ComponentActivity() {
private lateinit var authService: AuthService
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
authService = AuthService(this)
setContent {
DbcsTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
var username by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") }
var message by remember { mutableStateOf("") }
var securityLevel by remember { mutableStateOf("Unknown") }
Column(
modifier = Modifier
.padding(innerPadding)
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
OutlinedTextField(
value = username,
onValueChange = { username = it },
label = { Text("Username") },
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(8.dp))
OutlinedTextField(
value = password,
onValueChange = { password = it },
label = { Text("Password") },
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(16.dp))
Button(onClick = {
lifecycleScope.launch {
val success = authService.login(username, password)
message = if (success) "Login successful!" else "Login failed."
securityLevel = authService.keyManager.getKeySecurityLevel()
}
}) {
Text("Login")
}
Spacer(modifier = Modifier.height(8.dp))
Button(onClick = {
lifecycleScope.launch {
val success = authService.register(username, password)
message = if (success) "Registration successful!" else "Registration failed."
}
}) {
Text("Register")
}
Spacer(modifier = Modifier.height(8.dp))
Button(onClick = {
lifecycleScope.launch {
val isAuthenticated = authService.checkAuthentication()
message = if (isAuthenticated) "Authenticated!" else "Not authenticated."
}
}) {
Text("Check Auth")
}
Spacer(modifier = Modifier.height(16.dp))
Text("Security Level: $securityLevel", style = MaterialTheme.typography.bodyLarge)
Spacer(modifier = Modifier.height(16.dp))
Text(message)
}
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
style = MaterialTheme.typography.titleLarge,
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
DbcsTheme {
Greeting("DBCS")
}
}

View File

@@ -0,0 +1,11 @@
package fan.ovo.hwsign.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)

View File

@@ -0,0 +1,58 @@
package fan.ovo.hwsign.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun DbcsTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}

View File

@@ -0,0 +1,25 @@
package fan.ovo.hwsign.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
),
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Bold,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
)
)

View File

@@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#3DDC84"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
</vector>

View File

@@ -0,0 +1,30 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
<aapt:attr name="android:fillColor">
<gradient
android:endX="85.84757"
android:endY="92.4963"
android:startX="42.9492"
android:startY="49.59793"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 982 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
</resources>

View File

@@ -0,0 +1,3 @@
<resources>
<string name="app_name">dbcs</string>
</resources>

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Dbcs" parent="android:Theme.Material.Light.NoActionBar" />
</resources>

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?><!--
Sample backup rules file; uncomment and customize as necessary.
See https://developer.android.com/guide/topics/data/autobackup
for details.
Note: This file is ignored for devices older than API 31
See https://developer.android.com/about/versions/12/backup-restore
-->
<full-backup-content>
<!--
<include domain="sharedpref" path="."/>
<exclude domain="sharedpref" path="device.xml"/>
-->
</full-backup-content>

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?><!--
Sample data extraction rules file; uncomment and customize as necessary.
See https://developer.android.com/about/versions/12/backup-restore#xml-changes
for details.
-->
<data-extraction-rules>
<cloud-backup>
<!-- TODO: Use <include> and <exclude> to control what is backed up.
<include .../>
<exclude .../>
-->
</cloud-backup>
<!--
<device-transfer>
<include .../>
<exclude .../>
</device-transfer>
-->
</data-extraction-rules>

View File

@@ -0,0 +1,17 @@
package fan.ovo.hwsign
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}

View File

@@ -0,0 +1,6 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
alias(libs.plugins.android.application) apply false
alias(libs.plugins.kotlin.android) apply false
alias(libs.plugins.kotlin.compose) apply false
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,23 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. For more details, visit
# https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
# Enables namespacing of each library's R class so that its R class includes only the
# resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library
android.nonTransitiveRClass=true

View File

@@ -0,0 +1,39 @@
[versions]
agp = "8.9.1"
json = "20210307"
kotlin = "2.0.21"
coreKtx = "1.10.1"
junit = "4.13.2"
junitVersion = "1.2.1"
espressoCore = "3.6.1"
lifecycleRuntimeKtx = "2.6.1"
activityCompose = "1.8.0"
composeBom = "2024.09.00"
okhttp = "4.9.3"
securityCryptoKtx = "1.0.0"
[libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
androidx-security-crypto = { module = "androidx.security:security-crypto" }
json = { module = "org.json:json", version.ref = "json" }
junit = { group = "junit", name = "junit", version.ref = "junit" }
androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" }
androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" }
androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycleRuntimeKtx" }
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
androidx-ui = { group = "androidx.compose.ui", name = "ui" }
androidx-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
androidx-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
androidx-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
androidx-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" }
androidx-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" }
androidx-material3 = { group = "androidx.compose.material3", name = "material3" }
androidx-security-crypto-ktx = { group = "androidx.security", name = "security-crypto-ktx", version.ref = "securityCryptoKtx" }
okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }

Binary file not shown.

View File

@@ -0,0 +1,6 @@
#Mon Mar 31 19:52:01 CST 2025
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

185
hw-sign-android/gradlew vendored Normal file
View File

@@ -0,0 +1,185 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

89
hw-sign-android/gradlew.bat vendored Normal file
View File

@@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1,24 @@
pluginManagement {
repositories {
google {
content {
includeGroupByRegex("com\\.android.*")
includeGroupByRegex("com\\.google.*")
includeGroupByRegex("androidx.*")
}
}
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "dbcs"
include(":app")

View File

@@ -0,0 +1,356 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 77;
objects = {
/* Begin PBXFileReference section */
7195F3972D9A86CC00FA3526 /* hw-sign-apple.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "hw-sign-apple.app"; sourceTree = BUILT_PRODUCTS_DIR; };
7195F3AF2D9A87C700FA3526 /* hw-sign-apple.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = "hw-sign-apple.xcodeproj"; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedRootGroup section */
7195F3992D9A86CC00FA3526 /* hw-sign-apple */ = {
isa = PBXFileSystemSynchronizedRootGroup;
path = "hw-sign-apple";
sourceTree = "<group>";
};
/* End PBXFileSystemSynchronizedRootGroup section */
/* Begin PBXFrameworksBuildPhase section */
7195F3942D9A86CC00FA3526 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
7195F38E2D9A86CC00FA3526 = {
isa = PBXGroup;
children = (
7195F3992D9A86CC00FA3526 /* hw-sign-apple */,
7195F3982D9A86CC00FA3526 /* Products */,
);
sourceTree = "<group>";
};
7195F3982D9A86CC00FA3526 /* Products */ = {
isa = PBXGroup;
children = (
7195F3972D9A86CC00FA3526 /* hw-sign-apple.app */,
);
name = Products;
sourceTree = "<group>";
};
7195F3B02D9A87C700FA3526 /* Products */ = {
isa = PBXGroup;
name = Products;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
7195F3962D9A86CC00FA3526 /* hw-sign-apple */ = {
isa = PBXNativeTarget;
buildConfigurationList = 7195F3A62D9A86CD00FA3526 /* Build configuration list for PBXNativeTarget "hw-sign-apple" */;
buildPhases = (
7195F3932D9A86CC00FA3526 /* Sources */,
7195F3942D9A86CC00FA3526 /* Frameworks */,
7195F3952D9A86CC00FA3526 /* Resources */,
);
buildRules = (
);
dependencies = (
);
fileSystemSynchronizedGroups = (
7195F3992D9A86CC00FA3526 /* hw-sign-apple */,
);
name = "hw-sign-apple";
packageProductDependencies = (
);
productName = "hw-sign-apple";
productReference = 7195F3972D9A86CC00FA3526 /* hw-sign-apple.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
7195F38F2D9A86CC00FA3526 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1620;
LastUpgradeCheck = 1620;
TargetAttributes = {
7195F3962D9A86CC00FA3526 = {
CreatedOnToolsVersion = 16.2;
};
};
};
buildConfigurationList = 7195F3922D9A86CC00FA3526 /* Build configuration list for PBXProject "hw-sign-apple" */;
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 7195F38E2D9A86CC00FA3526;
minimizedProjectReferenceProxies = 1;
preferredProjectObjectVersion = 77;
productRefGroup = 7195F3982D9A86CC00FA3526 /* Products */;
projectDirPath = "";
projectReferences = (
{
ProductGroup = 7195F3B02D9A87C700FA3526 /* Products */;
ProjectRef = 7195F3AF2D9A87C700FA3526 /* hw-sign-apple.xcodeproj */;
},
);
projectRoot = "";
targets = (
7195F3962D9A86CC00FA3526 /* hw-sign-apple */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
7195F3952D9A86CC00FA3526 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
7195F3932D9A86CC00FA3526 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
7195F3A42D9A86CD00FA3526 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
7195F3A52D9A86CD00FA3526 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SWIFT_COMPILATION_MODE = wholemodule;
};
name = Release;
};
7195F3A72D9A86CD00FA3526 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = "hw-sign-apple/hw_sign_apple.entitlements";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_ASSET_PATHS = "\"hw-sign-apple/Preview Content\"";
DEVELOPMENT_TEAM = XV53H7ABC6;
ENABLE_HARDENED_RUNTIME = YES;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = YES;
"INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES;
"INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphonesimulator*]" = YES;
"INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphoneos*]" = YES;
"INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphonesimulator*]" = YES;
"INFOPLIST_KEY_UILaunchScreen_Generation[sdk=iphoneos*]" = YES;
"INFOPLIST_KEY_UILaunchScreen_Generation[sdk=iphonesimulator*]" = YES;
"INFOPLIST_KEY_UIStatusBarStyle[sdk=iphoneos*]" = UIStatusBarStyleDefault;
"INFOPLIST_KEY_UIStatusBarStyle[sdk=iphonesimulator*]" = UIStatusBarStyleDefault;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
IPHONEOS_DEPLOYMENT_TARGET = 18.2;
LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks";
"LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks";
MACOSX_DEPLOYMENT_TARGET = 15.2;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = fan.ovo.hwsign;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = auto;
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx xros xrsimulator";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2,7";
XROS_DEPLOYMENT_TARGET = 2.2;
};
name = Debug;
};
7195F3A82D9A86CD00FA3526 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = "hw-sign-apple/hw_sign_apple.entitlements";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_ASSET_PATHS = "\"hw-sign-apple/Preview Content\"";
DEVELOPMENT_TEAM = XV53H7ABC6;
ENABLE_HARDENED_RUNTIME = YES;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = YES;
"INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES;
"INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphonesimulator*]" = YES;
"INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphoneos*]" = YES;
"INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents[sdk=iphonesimulator*]" = YES;
"INFOPLIST_KEY_UILaunchScreen_Generation[sdk=iphoneos*]" = YES;
"INFOPLIST_KEY_UILaunchScreen_Generation[sdk=iphonesimulator*]" = YES;
"INFOPLIST_KEY_UIStatusBarStyle[sdk=iphoneos*]" = UIStatusBarStyleDefault;
"INFOPLIST_KEY_UIStatusBarStyle[sdk=iphonesimulator*]" = UIStatusBarStyleDefault;
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight";
IPHONEOS_DEPLOYMENT_TARGET = 18.2;
LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks";
"LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks";
MACOSX_DEPLOYMENT_TARGET = 15.2;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = fan.ovo.hwsign;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = auto;
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx xros xrsimulator";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2,7";
XROS_DEPLOYMENT_TARGET = 2.2;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
7195F3922D9A86CC00FA3526 /* Build configuration list for PBXProject "hw-sign-apple" */ = {
isa = XCConfigurationList;
buildConfigurations = (
7195F3A42D9A86CD00FA3526 /* Debug */,
7195F3A52D9A86CD00FA3526 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
7195F3A62D9A86CD00FA3526 /* Build configuration list for PBXNativeTarget "hw-sign-apple" */ = {
isa = XCConfigurationList;
buildConfigurations = (
7195F3A72D9A86CD00FA3526 /* Debug */,
7195F3A82D9A86CD00FA3526 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 7195F38F2D9A86CC00FA3526 /* Project object */;
}

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>

View File

@@ -0,0 +1,60 @@
import SwiftUI
@main
struct HWSignApp: App {
#if os(macOS)
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
#endif
@StateObject private var themeManager = ThemeManager()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(themeManager)
#if os(macOS)
.frame(minWidth: 400, minHeight: 400)
#endif
.preferredColorScheme(themeManager.isDarkMode ? .dark : .light)
}
#if os(macOS)
.windowStyle(HiddenTitleBarWindowStyle())
#endif
}
}
#if os(macOS)
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
// Setup macOS specific behavior if needed
let appearance =
UserDefaults.standard.bool(forKey: "isDarkMode")
? NSAppearance(named: .darkAqua) : NSAppearance(named: .aqua)
NSApp.appearance = appearance
}
}
#endif
class ThemeManager: ObservableObject {
@Published var isDarkMode: Bool {
didSet {
UserDefaults.standard.set(isDarkMode, forKey: "isDarkMode")
#if os(macOS)
NSApp.appearance = NSAppearance(named: isDarkMode ? .darkAqua : .aqua)
#endif
}
}
init() {
// Use saved preference or default to system setting
if UserDefaults.standard.object(forKey: "isDarkMode") != nil {
self.isDarkMode = UserDefaults.standard.bool(forKey: "isDarkMode")
} else {
#if os(iOS)
self.isDarkMode = UITraitCollection.current.userInterfaceStyle == .dark
#else
self.isDarkMode = false
#endif
}
}
}

View File

@@ -0,0 +1,11 @@
{
"colors" : [
{
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

View File

@@ -0,0 +1,85 @@
{
"images" : [
{
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "tinted"
}
],
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
},
{
"idiom" : "mac",
"scale" : "1x",
"size" : "16x16"
},
{
"idiom" : "mac",
"scale" : "2x",
"size" : "16x16"
},
{
"idiom" : "mac",
"scale" : "1x",
"size" : "32x32"
},
{
"idiom" : "mac",
"scale" : "2x",
"size" : "32x32"
},
{
"idiom" : "mac",
"scale" : "1x",
"size" : "128x128"
},
{
"idiom" : "mac",
"scale" : "2x",
"size" : "128x128"
},
{
"idiom" : "mac",
"scale" : "1x",
"size" : "256x256"
},
{
"idiom" : "mac",
"scale" : "2x",
"size" : "256x256"
},
{
"idiom" : "mac",
"scale" : "1x",
"size" : "512x512"
},
{
"idiom" : "mac",
"scale" : "2x",
"size" : "512x512"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

View File

@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}

View File

@@ -0,0 +1,200 @@
import Combine
import SwiftUI
struct ContentView: View {
@StateObject private var viewModel = AuthViewModel()
@EnvironmentObject private var themeManager: ThemeManager
var body: some View {
VStack(spacing: 20) {
Text("Hardware Secure Authentication")
.font(.largeTitle)
.fontWeight(.bold)
.padding()
.multilineTextAlignment(.center)
if !viewModel.isAuthenticated {
// Login/Registration Form
loginForm
} else {
// Authenticated View
authenticatedView
}
// Message display
Text(viewModel.message)
.foregroundColor(
viewModel.message.contains("successful") || viewModel.message.contains("verified")
? .green : .red
)
.padding()
.frame(minHeight: 60)
Spacer()
// Dark Mode Toggle
Toggle("Dark Mode", isOn: $themeManager.isDarkMode)
.padding(.horizontal)
}
.padding()
.disabled(viewModel.isLoading)
}
private var loginForm: some View {
Group {
TextField("Username", text: $viewModel.username)
.textFieldStyle(RoundedBorderTextFieldStyle())
.disableAutocorrection(true)
.padding(.horizontal)
SecureField("Password", text: $viewModel.password)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding(.horizontal)
HStack(spacing: 20) {
Button("Register") {
viewModel.handleRegister()
}
.buttonStyle(.borderedProminent)
.disabled(viewModel.isLoading)
Button("Login") {
viewModel.handleLogin()
}
.buttonStyle(.borderedProminent)
.disabled(viewModel.isLoading)
}
}
}
private var authenticatedView: some View {
Group {
Text("You are authenticated with hardware security!")
.font(.headline)
.foregroundColor(.green)
.padding()
Button("Check Authentication") {
viewModel.checkAuthentication()
}
.buttonStyle(.borderedProminent)
.disabled(viewModel.isLoading)
Button("Logout") {
viewModel.handleLogout()
}
.buttonStyle(.bordered)
.foregroundColor(.red)
.padding(.top)
.disabled(viewModel.isLoading)
}
}
}
class AuthViewModel: ObservableObject {
@Published var username = ""
@Published var password = ""
@Published var message = ""
@Published var isAuthenticated = false
@Published var isLoading = false
private var cancellables = Set<AnyCancellable>()
private let authService = AuthService.shared
init() {
// Check if user is already authenticated
isAuthenticated = KeyManager.shared.getAuthToken() != nil
}
func handleRegister() {
guard !username.isEmpty, !password.isEmpty else {
message = "Username and password required"
return
}
isLoading = true
message = "Registering..."
authService.register(username: username, password: password)
.receive(on: DispatchQueue.main)
.sink(
receiveCompletion: { [weak self] completion in
guard let self = self else { return }
self.isLoading = false
if case let .failure(error) = completion {
self.message = "Registration failed: \(error.localizedDescription)"
}
},
receiveValue: { [weak self] response in
guard let self = self else { return }
self.message = response
}
)
.store(in: &cancellables)
}
func handleLogin() {
guard !username.isEmpty, !password.isEmpty else {
message = "Username and password required"
return
}
isLoading = true
message = "Logging in..."
authService.login(username: username, password: password)
.receive(on: DispatchQueue.main)
.sink(
receiveCompletion: { [weak self] completion in
guard let self = self else { return }
self.isLoading = false
if case let .failure(error) = completion {
self.message = "Login failed: \(error.localizedDescription)"
}
},
receiveValue: { [weak self] response in
guard let self = self else { return }
self.isAuthenticated = true
self.message = response
}
)
.store(in: &cancellables)
}
func checkAuthentication() {
isLoading = true
message = "Checking authentication..."
authService.checkAuthentication()
.receive(on: DispatchQueue.main)
.sink(
receiveCompletion: { [weak self] completion in
guard let self = self else { return }
self.isLoading = false
if case let .failure(error) = completion {
self.message = "Authentication check failed: \(error.localizedDescription)"
}
},
receiveValue: { [weak self] response in
guard let self = self else { return }
self.message = response
}
)
.store(in: &cancellables)
}
func handleLogout() {
authService.logout()
isAuthenticated = false
message = "Logged out successfully"
}
}
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environmentObject(ThemeManager())
}
}
#endif

View File

@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}

View File

@@ -0,0 +1,283 @@
import Combine
import Foundation
import Security
class AuthService {
static let shared = AuthService()
private let baseURL = URL(string: "https://dbcs-api.ovo.fan")!
// private let baseURL = URL(string: "http://127.0.0.1:28280")!
private let keyManager = KeyManager.shared
private var cancellables = Set<AnyCancellable>()
private init() {}
// MARK: - Authentication Flow
func register(username: String, password: String) -> AnyPublisher<String, Error> {
let body = ["username": username, "password": password]
return makeRequest("register", method: "POST", body: body, responseType: EmptyResponse.self)
.map { _ in "Registration successful!" }
.eraseToAnyPublisher()
}
func login(username: String, password: String) -> AnyPublisher<String, Error> {
return Future { [weak self] promise in
guard let self = self else {
promise(
.failure(
NSError(
domain: "AuthService", code: -1,
userInfo: [NSLocalizedDescriptionKey: "Service unavailable"])))
return
}
do {
// Create new hardware key for this session
let hwKey = try self.keyManager.createKey(.hardware, forceNew: true)
guard let hwPubKey = self.keyManager.getPublicKey(for: hwKey) else {
throw NSError(
domain: "AuthService", code: -1,
userInfo: [NSLocalizedDescriptionKey: "Failed to get public key"])
}
let hwPubKeyData = try self.keyManager.exportPublicKey(hwPubKey)
let hwPubKeyBase64 = hwPubKeyData.base64EncodedString()
// Make login request with hardware key
let body = ["username": username, "password": password]
var request = try self.createRequest("login", method: "POST", body: body)
request.setValue(hwPubKeyBase64, forHTTPHeaderField: "x-rpc-sec-bound-token-hw-pub")
request.setValue("ecdsa", forHTTPHeaderField: "x-rpc-sec-bound-token-hw-pub-type") // Always use ECDSA
URLSession.shared.dataTaskPublisher(for: request)
.tryMap { data, response -> Data in
guard let httpResponse = response as? HTTPURLResponse else {
throw NSError(
domain: "AuthService", code: -1,
userInfo: [NSLocalizedDescriptionKey: "Invalid response type"])
}
if !(200...299).contains(httpResponse.statusCode) {
throw NSError(
domain: "AuthService", code: httpResponse.statusCode,
userInfo: [NSLocalizedDescriptionKey: "Server error: \(httpResponse.statusCode)"])
}
return data
}
.decode(type: LoginResponse.self, decoder: JSONDecoder())
.receive(on: DispatchQueue.main)
.sink(
receiveCompletion: { completion in
if case let .failure(error) = completion {
promise(.failure(error))
}
},
receiveValue: { response in
self.keyManager.storeAuthToken(response.token)
promise(.success("Login successful!"))
}
)
.store(in: &self.cancellables)
} catch {
promise(.failure(error))
}
}.eraseToAnyPublisher()
}
func checkAuthentication() -> AnyPublisher<String, Error> {
return authenticatedRequest("authenticated", method: "GET", responseType: AuthResponse.self)
.map { _ in "Authentication verified with hardware security!" }
.eraseToAnyPublisher()
}
func logout() {
try? keyManager.deleteKey(.hardware)
try? keyManager.deleteKey(.acceleration)
keyManager.deleteAuthToken()
keyManager.deleteAccelKeyId()
}
// MARK: - Request Helpers
private func makeRequest<T: Codable>(
_ path: String, method: String, body: [String: Any]? = nil, responseType: T.Type
) -> AnyPublisher<T, Error> {
return Future { [weak self] promise in
guard let self = self else {
promise(
.failure(
NSError(
domain: "AuthService", code: -1,
userInfo: [NSLocalizedDescriptionKey: "Service unavailable"])))
return
}
do {
let request = try self.createRequest(path, method: method, body: body)
URLSession.shared.dataTaskPublisher(for: request)
.tryMap { data, response -> Data in
guard let httpResponse = response as? HTTPURLResponse else {
throw NSError(
domain: "AuthService", code: -1,
userInfo: [NSLocalizedDescriptionKey: "Invalid response type"])
}
if !(200...299).contains(httpResponse.statusCode) {
throw NSError(
domain: "AuthService", code: httpResponse.statusCode,
userInfo: [NSLocalizedDescriptionKey: "Server error: \(httpResponse.statusCode)"])
}
return data
}
.decode(type: T.self, decoder: JSONDecoder())
.receive(on: DispatchQueue.main)
.sink(
receiveCompletion: { completion in
if case let .failure(error) = completion {
promise(.failure(error))
}
},
receiveValue: { response in
promise(.success(response))
}
)
.store(in: &self.cancellables)
} catch {
promise(.failure(error))
}
}.eraseToAnyPublisher()
}
private func authenticatedRequest<T: Codable>(
_ path: String, method: String, responseType: T.Type, body: [String: Any]? = nil
) -> AnyPublisher<T, Error> {
return Future { [weak self] promise in
guard let self = self else {
promise(
.failure(
NSError(
domain: "AuthService", code: -1,
userInfo: [NSLocalizedDescriptionKey: "Service unavailable"])))
return
}
do {
let timestamp = String(Int(Date().timeIntervalSince1970))
let accelKeyId = self.keyManager.getAccelKeyId()
var request = try self.createRequest(path, method: method, body: body)
request.setValue(
"Bearer \(self.keyManager.getAuthToken() ?? "")", forHTTPHeaderField: "Authorization")
request.setValue(timestamp, forHTTPHeaderField: "x-rpc-sec-bound-token-data")
if let accelKeyId = accelKeyId {
// Use existing acceleration key
let accelKey = try self.keyManager.loadKey(.acceleration)
let signature = try self.keyManager.sign(
data: timestamp.data(using: .utf8)!, with: accelKey)
request.setValue(
signature.base64EncodedString(), forHTTPHeaderField: "x-rpc-sec-bound-token-data-sig")
request.setValue(accelKeyId, forHTTPHeaderField: "x-rpc-sec-bound-token-accel-pub-id")
} else {
// Create new acceleration key
let accelKey = try self.keyManager.createKey(.acceleration)
guard let accelPubKey = self.keyManager.getPublicKey(for: accelKey) else {
throw NSError(
domain: "AuthService", code: -1,
userInfo: [NSLocalizedDescriptionKey: "Failed to get acceleration public key"])
}
let accelPubKeyData = try self.keyManager.exportPublicKey(accelPubKey)
let accelPubKeyBase64 = accelPubKeyData.base64EncodedString()
// Sign acceleration key with hardware key
let hwKey = try self.keyManager.loadKey(.hardware)
let accelKeySig = try self.keyManager.sign(
data: accelPubKeyBase64.data(using: .utf8)!, with: hwKey)
let signature = try self.keyManager.sign(
data: timestamp.data(using: .utf8)!, with: accelKey)
request.setValue(accelPubKeyBase64, forHTTPHeaderField: "x-rpc-sec-bound-token-accel-pub")
request.setValue("ecdsa", forHTTPHeaderField: "x-rpc-sec-bound-token-accel-pub-type") // Always use ECDSA
request.setValue(
accelKeySig.base64EncodedString(), forHTTPHeaderField: "x-rpc-sec-bound-token-accel-pub-sig")
request.setValue(
signature.base64EncodedString(), forHTTPHeaderField: "x-rpc-sec-bound-token-data-sig")
}
URLSession.shared.dataTaskPublisher(for: request)
.tryMap { data, response -> Data in
guard let httpResponse = response as? HTTPURLResponse else {
throw NSError(
domain: "AuthService", code: -1,
userInfo: [NSLocalizedDescriptionKey: "Invalid response type"])
}
if let accelKeyId = httpResponse.value(
forHTTPHeaderField: "x-rpc-sec-bound-token-accel-pub-id")
{
self.keyManager.storeAccelKeyId(accelKeyId)
}
if !(200...299).contains(httpResponse.statusCode) {
throw NSError(
domain: "AuthService", code: httpResponse.statusCode,
userInfo: [NSLocalizedDescriptionKey: "Server error: \(httpResponse.statusCode)"])
}
return data
}
.decode(type: T.self, decoder: JSONDecoder())
.receive(on: DispatchQueue.main)
.sink(
receiveCompletion: { completion in
if case let .failure(error) = completion {
promise(.failure(error))
}
},
receiveValue: { response in
promise(.success(response))
}
)
.store(in: &self.cancellables)
} catch {
promise(.failure(error))
}
}.eraseToAnyPublisher()
}
private func createRequest(_ path: String, method: String, body: [String: Any]? = nil) throws
-> URLRequest
{
var request = URLRequest(url: baseURL.appendingPathComponent(path))
request.httpMethod = method
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
if let body = body {
request.httpBody = try JSONSerialization.data(withJSONObject: body)
}
return request
}
}
// MARK: - Response Models
struct LoginResponse: Codable {
let token: String
}
struct AuthResponse: Codable {
let authenticated: Bool
}
struct EmptyResponse: Codable {
// Empty response structure for endpoints that don't return meaningful data
}

View File

@@ -0,0 +1,149 @@
import Foundation
import LocalAuthentication
import Security
class KeyManager {
static let shared = KeyManager()
private let tagPrefix = "fan.ovo.hwsign"
enum KeyType: String {
case hardware = "hardware"
case acceleration = "acceleration"
}
private init() {}
// MARK: - Key Management
func createKey(_ type: KeyType, forceNew: Bool = false) throws -> SecKey {
let tag = "\(tagPrefix).\(type.rawValue)"
// Always attempt to delete an existing key with the same tag to avoid conflicts
try? deleteKey(type)
let flags: SecAccessControlCreateFlags = [.privateKeyUsage]
let access = SecAccessControlCreateWithFlags(
kCFAllocatorDefault,
kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
flags,
nil
)!
let attributes: [String: Any] = [
kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
kSecAttrKeySizeInBits as String: 256,
kSecAttrTokenID as String: kSecAttrTokenIDSecureEnclave,
kSecPrivateKeyAttrs as String: [
kSecAttrIsPermanent as String: true,
kSecAttrAccessControl as String: access,
kSecAttrApplicationTag as String: tag.data(using: .utf8)!,
],
]
var error: Unmanaged<CFError>?
guard let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {
throw error!.takeRetainedValue() as Error
}
return privateKey
}
func loadKey(_ type: KeyType) throws -> SecKey {
let tag = "\(tagPrefix).\(type.rawValue)"
let query: [String: Any] = [
kSecClass as String: kSecClassKey,
kSecAttrApplicationTag as String: tag.data(using: .utf8)!,
kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
kSecReturnRef as String: true,
]
var item: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &item)
guard status == errSecSuccess else {
throw NSError(domain: NSOSStatusErrorDomain, code: Int(status))
}
// Fix: Use proper type safety pattern instead of direct force casting
guard let key = item else {
throw NSError(
domain: "KeyManager", code: -1,
userInfo: [NSLocalizedDescriptionKey: "Retrieved key is nil"])
}
return (key as! SecKey) // This cast is safe because SecItemCopyMatching guarantees a SecKey when using kSecReturnRef
}
func deleteKey(_ type: KeyType) throws {
let tag = "\(tagPrefix).\(type.rawValue)"
let query: [String: Any] = [
kSecClass as String: kSecClassKey,
kSecAttrApplicationTag as String: tag.data(using: .utf8)!,
]
let status = SecItemDelete(query as CFDictionary)
guard status == errSecSuccess || status == errSecItemNotFound else {
throw NSError(domain: NSOSStatusErrorDomain, code: Int(status))
}
}
// MARK: - Signing Operations
func sign(data: Data, with key: SecKey) throws -> Data {
var error: Unmanaged<CFError>?
guard
let signature = SecKeyCreateSignature(
key,
.ecdsaSignatureMessageX962SHA256,
data as CFData,
&error
) as Data?
else {
throw error!.takeRetainedValue() as Error
}
return signature
}
func getPublicKey(for privateKey: SecKey) -> SecKey? {
return SecKeyCopyPublicKey(privateKey)
}
func exportPublicKey(_ key: SecKey) throws -> Data {
// This encodes ec public to x962
var error: Unmanaged<CFError>?
guard let exportedKey = SecKeyCopyExternalRepresentation(key, &error) as Data? else {
throw error!.takeRetainedValue() as Error
}
return exportedKey
}
// MARK: - Token Management
func storeAuthToken(_ token: String) {
UserDefaults.standard.set(token, forKey: "\(tagPrefix).authToken")
}
func getAuthToken() -> String? {
return UserDefaults.standard.string(forKey: "\(tagPrefix).authToken")
}
func deleteAuthToken() {
UserDefaults.standard.removeObject(forKey: "\(tagPrefix).authToken")
}
func storeAccelKeyId(_ keyId: String) {
UserDefaults.standard.set(keyId, forKey: "\(tagPrefix).accelKeyId")
}
func getAccelKeyId() -> String? {
return UserDefaults.standard.string(forKey: "\(tagPrefix).accelKeyId")
}
func deleteAccelKeyId() {
UserDefaults.standard.removeObject(forKey: "\(tagPrefix).accelKeyId")
}
}

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.app-sandbox</key>
<true/>
<key>com.apple.security.files.user-selected</key>
<true/>
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.network.dns</key>
<true/>
<key>com.apple.security.network.server</key>
<true/>
<key>keychain-access-groups</key>
<array/>
</dict>
</plist>

30
hw-sign-browser/.gitignore vendored Normal file
View File

@@ -0,0 +1,30 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
.DS_Store
dist
dist-ssr
coverage
*.local
/cypress/videos/
/cypress/screenshots/
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
*.tsbuildinfo

33
hw-sign-browser/README.md Normal file
View File

@@ -0,0 +1,33 @@
# hw-sign-browser
This template should help get you started developing with Vue 3 in Vite.
## Recommended IDE Setup
[VSCode](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur).
## Type Support for `.vue` Imports in TS
TypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) to make the TypeScript language service aware of `.vue` types.
## Customize configuration
See [Vite Configuration Reference](https://vite.dev/config/).
## Project Setup
```sh
npm install
```
### Compile and Hot-Reload for Development
```sh
npm run dev
```
### Type-Check, Compile and Minify for Production
```sh
npm run build
```

1
hw-sign-browser/env.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
/// <reference types="vite/client" />

View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DBCS Demo</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

View File

@@ -0,0 +1,31 @@
{
"name": "hw-sign-browser",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --port 3000",
"build": "run-p type-check \"build-only {@}\" --",
"preview": "vite preview",
"build-only": "vite build",
"type-check": "vue-tsc --build"
},
"dependencies": {
"axios": "^1.8.4",
"vue": "^3.5.13"
},
"devDependencies": {
"@tsconfig/node22": "^22.0.0",
"@types/node": "^22.13.9",
"@vitejs/plugin-vue": "^5.2.1",
"@vue/tsconfig": "^0.7.0",
"autoprefixer": "^10.4.21",
"npm-run-all2": "^7.0.2",
"postcss": "^8.5.3",
"tailwindcss": "3",
"typescript": "~5.8.0",
"vite": "^6.2.1",
"vite-plugin-vue-devtools": "^7.7.2",
"vue-tsc": "^2.2.8"
}
}

2886
hw-sign-browser/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

260
hw-sign-browser/src/App.vue Normal file
View File

@@ -0,0 +1,260 @@
<script setup lang="ts">
import { ref, watch, onMounted, computed } from 'vue';
import {
register,
login,
logout,
isAuthenticated as checkAuthService,
toggleSymmetricEncryption,
isSymmetricEncryptionEnabled
} from './services/authService';
// Reactive state
const isAuthenticated = ref(false);
const message = ref('');
const username = ref('');
const password = ref('');
const darkMode = ref(false);
const isLoading = ref(false);
const useSymmetric = ref(true);
// Computed properties for UI state
const messageClass = computed(() => ({
'text-green-600 dark:text-green-400': message.value.includes('successful'),
'text-red-600 dark:text-red-400': !message.value.includes('successful')
}));
const formIsValid = computed(() => username.value && password.value);
// Auth handlers
async function handleRegister() {
if (!formIsValid.value) {
message.value = 'Please enter both username and password';
return;
}
await performAuthOperation(async () => {
await register({ username: username.value, password: password.value });
return 'Registration successful! Please log in.';
});
}
async function handleLogin() {
if (!formIsValid.value) {
message.value = 'Please enter both username and password';
return;
}
await performAuthOperation(async () => {
await login({ username: username.value, password: password.value });
isAuthenticated.value = true;
return 'Login successful!';
});
}
function handleLogout() {
logout();
isAuthenticated.value = false;
}
async function checkAuthentication() {
await performAuthOperation(async () => {
const authenticated = await checkAuthService();
return authenticated
? 'You are successfully authenticated and token protected by hardware!'
: 'You are not authenticated, something went wrong.';
});
}
async function handleToggleEncryption() {
try {
useSymmetric.value = await toggleSymmetricEncryption();
message.value = `Encryption mode changed to ${useSymmetric.value ? 'symmetric (ECDH/HMAC)' : 'asymmetric (signature-based)'}`;
} catch (error) {
console.error('Failed to toggle encryption mode:', error);
message.value = 'Failed to change encryption mode';
}
}
// Helper function to reduce repetitive code in auth operations
async function performAuthOperation(operation: () => Promise<string>) {
isLoading.value = true;
try {
message.value = await operation();
} catch (error) {
message.value = error instanceof Error ? error.message : 'Operation failed';
console.error('Auth operation failed:', error);
} finally {
isLoading.value = false;
}
}
// Toggle dark mode
function toggleDarkMode() {
darkMode.value = !darkMode.value;
}
// Initialization
onMounted(async () => {
try {
isLoading.value = true;
// Check initial auth state and load preferences
isAuthenticated.value = await checkAuthService();
useSymmetric.value = isSymmetricEncryptionEnabled();
// Setup dark mode based on saved preference or system preference
initializeDarkMode();
// Add cleanup handler
window.addEventListener('unload', () => {
if (!isAuthenticated.value) {
logout(); // Clean up IndexedDB if not authenticated
}
});
} catch (e) {
console.debug('Initial setup failed:', e);
} finally {
isLoading.value = false;
}
});
// Initialize dark mode based on saved preference or system preference
function initializeDarkMode() {
darkMode.value = localStorage.getItem('darkMode') === 'true' ||
(localStorage.getItem('darkMode') === null &&
window.matchMedia('(prefers-color-scheme: dark)').matches);
applyDarkMode();
}
// Apply dark mode to document
function applyDarkMode() {
if (darkMode.value) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
}
// Watch for dark mode changes to save preference and apply
watch(darkMode, (newValue) => {
localStorage.setItem('darkMode', newValue.toString());
applyDarkMode();
});
</script>
<template>
<div class="min-h-screen w-full flex items-center justify-center bg-gray-100 dark:bg-gray-900">
<!-- Loading overlay -->
<div v-if="isLoading" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center">
<div class="bg-white dark:bg-gray-800 rounded-lg p-4 flex flex-col items-center shadow-lg">
<svg class="animate-spin h-8 w-8 text-indigo-600 dark:text-indigo-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
</svg>
<p class="mt-4 text-gray-700 dark:text-gray-300">Processing...</p>
</div>
</div>
<div
class="w-full max-w-lg bg-white dark:bg-gray-800 rounded-lg shadow-lg p-8 border border-gray-200 dark:border-gray-700">
<h1 class="text-2xl font-bold text-center mb-6 text-gray-900 dark:text-gray-100">User Authentication</h1>
<!-- Login Form -->
<div v-if="!isAuthenticated" class="space-y-6">
<div>
<label for="username" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Username</label>
<input v-model="username" id="username" type="text" :disabled="isLoading"
class="mt-2 block w-full rounded-lg border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-gray-100 px-4 py-2"
placeholder="Enter your username" />
</div>
<div>
<label for="password" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Password</label>
<input v-model="password" id="password" type="password" :disabled="isLoading"
class="mt-2 block w-full rounded-lg border border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-gray-100 px-4 py-2"
placeholder="Enter your password" />
</div>
<div class="flex justify-between">
<button @click="handleRegister" :disabled="isLoading" class="btn-green">
Register
</button>
<button @click="handleLogin" :disabled="isLoading" class="btn-primary">
Login
</button>
</div>
</div>
<!-- Authenticated View -->
<div v-else class="text-center">
<p class="text-lg font-medium text-green-600 dark:text-green-400 mb-4">You are authenticated!</p>
<div class="space-y-4">
<button @click="checkAuthentication" :disabled="isLoading" class="btn-primary w-full">
Check Hardware Sign Status
</button>
<button @click="handleToggleEncryption" class="btn-yellow w-full">
{{ useSymmetric ? 'Using ECDH+HMAC (Faster)' : 'Using Asymmetric Signatures' }}
</button>
<button @click="handleLogout" class="btn-danger w-full">
Logout
</button>
</div>
</div>
<!-- Status message -->
<p class="mt-4 text-center text-sm" :class="messageClass">
{{ message ?? 'Ready' }}
</p>
<!-- Dark mode toggle -->
<div class="mt-6 flex justify-end">
<button @click="toggleDarkMode"
class="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 text-2xl">
{{ darkMode ? '☀️' : '🌙' }}
</button>
</div>
</div>
</div>
</template>
<style scoped>
body {
font-family: 'Inter', sans-serif;
}
/* Button styles */
.btn-primary {
@apply bg-indigo-600 text-white py-2 px-4 rounded-lg hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 dark:focus:ring-offset-gray-900 disabled:opacity-50 disabled:cursor-not-allowed;
}
.btn-green {
@apply bg-green-600 text-white py-2 px-4 rounded-lg hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 dark:focus:ring-offset-gray-900 disabled:opacity-50 disabled:cursor-not-allowed;
}
.btn-yellow {
@apply bg-yellow-600 text-white py-2 px-4 rounded-lg hover:bg-yellow-700 focus:outline-none focus:ring-2 focus:ring-yellow-500 focus:ring-offset-2 dark:focus:ring-offset-gray-900;
}
.btn-danger {
@apply bg-red-600 text-white py-2 px-4 rounded-lg hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2;
}
/* Add styles for the loading overlay */
.fixed {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.bg-opacity-50 {
background-color: rgba(0, 0, 0, 0.5);
}
.z-50 {
z-index: 50;
}
</style>

View File

@@ -0,0 +1,90 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
/* color palette from <https://github.com/vuejs/theme> */
:root {
--vt-c-white: #ffffff;
--vt-c-white-soft: #f8f8f8;
--vt-c-white-mute: #f2f2f2;
--vt-c-black: #181818;
--vt-c-black-soft: #222222;
--vt-c-black-mute: #282828;
--vt-c-indigo: #2c3e50;
--vt-c-divider-light-1: rgba(60, 60, 60, 0.29);
--vt-c-divider-light-2: rgba(60, 60, 60, 0.12);
--vt-c-divider-dark-1: rgba(84, 84, 84, 0.65);
--vt-c-divider-dark-2: rgba(84, 84, 84, 0.48);
--vt-c-text-light-1: var(--vt-c-indigo);
--vt-c-text-light-2: rgba(60, 60, 60, 0.66);
--vt-c-text-dark-1: var(--vt-c-white);
--vt-c-text-dark-2: rgba(235, 235, 235, 0.64);
}
/* semantic color variables for this project */
:root {
--color-background: var(--vt-c-white);
--color-background-soft: var(--vt-c-white-soft);
--color-background-mute: var(--vt-c-white-mute);
--color-border: var(--vt-c-divider-light-2);
--color-border-hover: var(--vt-c-divider-light-1);
--color-heading: var(--vt-c-text-light-1);
--color-text: var(--vt-c-text-light-1);
--section-gap: 160px;
}
@media (prefers-color-scheme: dark) {
:root {
--color-background: var(--vt-c-black);
--color-background-soft: var(--vt-c-black-soft);
--color-background-mute: var(--vt-c-black-mute);
--color-border: var(--vt-c-divider-dark-2);
--color-border-hover: var(--vt-c-divider-dark-1);
--color-heading: var(--vt-c-text-dark-1);
--color-text: var(--vt-c-text-dark-2);
}
}
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
font-weight: normal;
}
body {
min-height: 100vh;
color: var(--color-text);
background: var(--color-background);
transition:
color 0.5s,
background-color 0.5s;
line-height: 1.6;
font-family:
Inter,
-apple-system,
BlinkMacSystemFont,
'Segoe UI',
Roboto,
Oxygen,
Ubuntu,
Cantarell,
'Fira Sans',
'Droid Sans',
'Helvetica Neue',
sans-serif;
font-size: 15px;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 261.76 226.69"><path d="M161.096.001l-30.225 52.351L100.647.001H-.005l130.877 226.688L261.749.001z" fill="#41b883"/><path d="M161.096.001l-30.225 52.351L100.647.001H52.346l78.526 136.01L209.398.001z" fill="#34495e"/></svg>

After

Width:  |  Height:  |  Size: 276 B

View File

@@ -0,0 +1,20 @@
@import './base.css';
#app {
margin: 0 auto;
font-weight: normal;
}
a,
.green {
text-decoration: none;
color: hsla(160, 100%, 37%, 1);
transition: 0.4s;
padding: 3px;
}
@media (hover: hover) {
a:hover {
background-color: hsla(160, 100%, 37%, 0.2);
}
}

View File

@@ -0,0 +1,5 @@
import './assets/main.css';
import { createApp } from 'vue';
import App from './App.vue';
createApp(App).mount('#app');

View File

@@ -0,0 +1,701 @@
import axios, { AxiosError } from 'axios';
// Response type definitions
interface ServerResponse {
message?: string;
}
interface LoginResponse extends ServerResponse {
token: string;
}
interface AuthResponse extends ServerResponse {
authenticated: boolean;
}
const apiClient = axios.create({
baseURL: import.meta.env.DEV ? 'http://127.0.0.1:28280' : 'https://dbcs-api.ovo.fan',
headers: { 'Content-Type': 'application/json' },
});
// Storage constants
const DB_NAME = 'DBCS';
const DB_VERSION = 1;
const STORE_NAME = 'auth_data';
const HW_KEY_ID = 'hardware_key';
const AUTH_TOKEN_ID = 'auth_token';
const ACCEL_KEY_ID_STORE = 'accel_key_id';
const PREFER_SYMMETRIC_STORE = 'prefer_symmetric';
// In-memory state
let hardwareKey: CryptoKeyPair | null = null;
let accelerationKey: CryptoKeyPair | null = null;
let accelerationKeyId: string | null = null;
let ecdhAccelerationKey: CryptoKeyPair | null = null;
let symmetricKey: CryptoKey | null = null;
let preferSymmetricEncryption = true; // Default to true for better performance
// Add debug logger
function debugLog(step: string, message: string, data?: any): void {
const timestamp = new Date().toISOString();
console.debug(`[${timestamp}] [DBCS] ${step}: ${message}`, data || '');
}
// IndexedDB helper functions
async function openDB(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
request.onupgradeneeded = (event) => {
const db = (event.target as IDBOpenDBRequest).result;
if (!db.objectStoreNames.contains(STORE_NAME)) {
db.createObjectStore(STORE_NAME);
}
};
});
}
async function storeData(key: string, value: any): Promise<void> {
const db = await openDB();
return new Promise((resolve, reject) => {
const transaction = db.transaction(STORE_NAME, 'readwrite');
const store = transaction.objectStore(STORE_NAME);
const request = store.put(value, key);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve();
transaction.oncomplete = () => db.close();
});
}
async function loadData(key: string): Promise<any> {
const db = await openDB();
return new Promise((resolve, reject) => {
const transaction = db.transaction(STORE_NAME, 'readonly');
const store = transaction.objectStore(STORE_NAME);
const request = store.get(key);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result || null);
transaction.oncomplete = () => db.close();
});
}
async function deleteData(key: string): Promise<void> {
const db = await openDB();
return new Promise((resolve, reject) => {
const transaction = db.transaction(STORE_NAME, 'readwrite');
const store = transaction.objectStore(STORE_NAME);
const request = store.delete(key);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve();
transaction.oncomplete = () => db.close();
});
}
// Key storage wrappers
const storage = {
hardwareKey: {
store: (key: CryptoKeyPair) => storeData(HW_KEY_ID, key),
load: () => loadData(HW_KEY_ID) as Promise<CryptoKeyPair | null>,
delete: () => deleteData(HW_KEY_ID)
},
authToken: {
store: (token: string) => storeData(AUTH_TOKEN_ID, token),
load: () => loadData(AUTH_TOKEN_ID) as Promise<string | null>,
delete: () => deleteData(AUTH_TOKEN_ID)
},
preferSymmetric: {
store: (value: boolean) => storeData(PREFER_SYMMETRIC_STORE, value),
load: async () => {
const value = await loadData(PREFER_SYMMETRIC_STORE);
return value !== false; // Default to true if not set
}
}
};
// Supported key algorithms
type KeyAlgorithm = 'Ed25519' | 'ECDSA' | 'RSA-PSS' | 'ECDH';
// Generate keys with fallback support
async function tryGenerateKey(type: KeyAlgorithm, extractable: boolean): Promise<CryptoKeyPair | null> {
if (!window.crypto?.subtle) return null;
try {
debugLog('Key Generation', `Attempting to generate ${type} key, extractable: ${extractable}`);
switch (type) {
case 'Ed25519':
return await window.crypto.subtle.generateKey(
{ name: 'Ed25519' },
extractable,
['sign', 'verify']
);
case 'ECDSA':
return await window.crypto.subtle.generateKey(
{ name: 'ECDSA', namedCurve: 'P-256' },
extractable,
['sign', 'verify']
);
case 'RSA-PSS':
return await window.crypto.subtle.generateKey(
{
name: 'RSA-PSS',
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: 'SHA-256',
},
extractable,
['sign', 'verify']
);
case 'ECDH':
return await window.crypto.subtle.generateKey(
{ name: 'ECDH', namedCurve: 'P-256' },
extractable,
['deriveKey', 'deriveBits']
);
default:
return null;
}
} catch (e) {
debugLog('Key Generation', `Failed to generate ${type} key:`, e);
console.debug(`Failed to generate ${type} key:`, e);
return null;
}
}
async function generateKey(extractable: boolean, type?: KeyAlgorithm): Promise<CryptoKeyPair> {
if (!window.crypto?.subtle) {
debugLog('Key Generation', 'Web Crypto API not supported');
throw new Error('Web Crypto API not supported');
}
// If a specific algorithm is requested, try it first
if (type) {
const key = await tryGenerateKey(type, extractable);
if (key) {
console.debug(`Using ${type} for key`);
debugLog('Key Generation', `Successfully generated ${key.publicKey.algorithm.name} key`);
return key;
}
}
// Try algorithms in order of preference
const algorithms: KeyAlgorithm[] = ['Ed25519', 'ECDSA', 'RSA-PSS'];
for (const algo of algorithms) {
const key = await tryGenerateKey(algo, extractable);
if (key) {
console.debug(`Using ${algo} for ${extractable ? 'acceleration' : 'hardware'} key`);
debugLog('Key Generation', `Successfully generated ${key.publicKey.algorithm.name} key`);
return key;
}
}
throw new Error('No supported key algorithms available');
}
// Utility functions for data conversion and encryption
function arrayBufferToBase64(buffer: ArrayBuffer): string {
return btoa(String.fromCharCode(...new Uint8Array(buffer)));
}
function base64ToArrayBuffer(base64: string): ArrayBuffer {
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
async function exportPublicKey(key: CryptoKey): Promise<string> {
// Choose export format based on algorithm
const format = ['Ed25519', 'ECDH'].includes(key.algorithm.name) ? 'raw' : 'spki';
const exported = await window.crypto.subtle.exportKey(format, key);
return arrayBufferToBase64(exported);
}
// HMAC generation for ECDH-derived keys
async function generateHMAC(key: CryptoKey, data: string): Promise<string> {
debugLog('HMAC', `Generating HMAC for data (${data.length} chars)`, {
dataPreview: data.substring(0, 20) + '...',
keyAlgo: key.algorithm.name,
keyUsages: key.usages
});
const encoder = new TextEncoder();
const dataBuffer = encoder.encode(data);
const signature = await window.crypto.subtle.sign(
{ name: 'HMAC' },
key,
dataBuffer
);
debugLog('HMAC', `Generated HMAC: ${signature.byteLength} bytes`);
return arrayBufferToBase64(signature);
}
// Function to derive shared secret and create HMAC key
async function deriveSharedKey(privateKey: CryptoKey, publicKeyBase64: string): Promise<CryptoKey> {
debugLog('ECDH', 'Starting key derivation process', {
publicKeyLength: publicKeyBase64.length,
privateKeyAlgo: privateKey.algorithm.name
});
try {
// Import the server's public key
const publicKeyData = base64ToArrayBuffer(publicKeyBase64);
// Import the raw key data for ECDH
const serverPublicKey = await window.crypto.subtle.importKey(
'raw',
publicKeyData,
{ name: 'ECDH', namedCurve: 'P-256' },
false,
[]
);
// Derive bits from the ECDH exchange
const derivedBits = await window.crypto.subtle.deriveBits(
{ name: 'ECDH', public: serverPublicKey },
privateKey,
256 // 256 bits for HMAC key
);
debugLog('ECDH', 'Derived HMAC key successfully', {
derivedBitsLength: derivedBits.byteLength
});
// Create HMAC key from the derived bits
return await window.crypto.subtle.importKey(
'raw',
derivedBits,
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign', 'verify']
);
} catch (error) {
debugLog('ECDH', 'Failed to derive shared key', error);
console.error('Failed to derive shared key:', error);
throw new Error('Failed to derive HMAC key');
}
}
// Key management functions
async function setupECDHAccelerationKey(): Promise<{
ecdhPubKeyBase64: string;
ecdhPubKeySig: string;
}> {
debugLog('ECDH Setup', 'Generating ECDH acceleration key pair');
try {
// Generate ECDH key pair - set extractable to FALSE for better security
ecdhAccelerationKey = await generateKey(false, 'ECDH');
// Export the public key
const ecdhPubKeyBase64 = await exportPublicKey(ecdhAccelerationKey.publicKey);
debugLog('ECDH Setup', 'ECDH key pair generated successfully', {
publicKeyLength: ecdhPubKeyBase64.length
});
// Sign the public key with hardware key
const ecdhPubKeySig = await signWithKey(hardwareKey!.privateKey, ecdhPubKeyBase64);
debugLog('ECDH Setup', 'Signed ECDH public key with hardware key');
return { ecdhPubKeyBase64, ecdhPubKeySig };
} catch (error) {
debugLog('ECDH Setup', 'Failed to setup ECDH key', error);
console.error('Failed to setup ECDH key:', error);
throw error;
}
}
async function setupAccelerationKey(): Promise<{ accelPubKeyBase64: string; accelPubKeySig: string; keyType: string }> {
if (accelerationKey) {
const accelPubKeyBase64 = await exportPublicKey(accelerationKey.publicKey);
const accelPubKeySig = await signWithKey(hardwareKey!.privateKey, accelPubKeyBase64);
const keyType = accelerationKey.publicKey.algorithm.name.toLowerCase();
return { accelPubKeyBase64, accelPubKeySig, keyType };
}
try {
// Generate new acceleration key
accelerationKey = await generateKey(true);
// Export acceleration public key
const accelPubKeyBase64 = await exportPublicKey(accelerationKey.publicKey);
const accelPubKeySig = await signWithKey(hardwareKey!.privateKey, accelPubKeyBase64);
const keyType = accelerationKey.publicKey.algorithm.name.toLowerCase();
return { accelPubKeyBase64, accelPubKeySig, keyType };
} catch (error) {
// Reset the acceleration key on failure
accelerationKey = null;
accelerationKeyId = null;
throw error;
}
}
async function checkStorageSupport(): Promise<boolean> {
if (!window.indexedDB) return false;
try {
const db = await openDB();
db.close();
return true;
} catch (e) {
console.debug('IndexedDB not available:', e);
return false;
}
}
async function initHardwareKey(): Promise<void> {
debugLog('Hardware Key', 'Initializing hardware key');
if (hardwareKey) {
debugLog('Hardware Key', 'Hardware key already initialized');
return; // Already initialized
}
// Check storage support first
const hasStorage = await checkStorageSupport();
if (!hasStorage) {
throw new Error('Secure key storage is not available in your browser. Please enable IndexedDB or use a modern browser.');
}
// Try to load existing key first
hardwareKey = await storage.hardwareKey.load();
debugLog('Hardware Key', hardwareKey ? 'Loaded existing hardware key' : 'Generating new hardware key');
if (!hardwareKey) {
// Generate new key if none exists
hardwareKey = await generateKey(false); // Ensure hardware key is non-exportable
await storage.hardwareKey.store(hardwareKey);
}
debugLog('Hardware Key', 'Hardware key initialization complete');
}
async function init(): Promise<void> {
try {
// Load hardware key and auth token
await initHardwareKey();
// Load symmetric encryption preference
preferSymmetricEncryption = await storage.preferSymmetric.load();
} catch (error) {
console.error('Failed to initialize auth service', error);
}
}
async function signWithKey(key: CryptoKey, data: string): Promise<string> {
const dataBuffer = new TextEncoder().encode(data);
// Configure algorithm parameters based on key type
const params = key.algorithm.name === 'RSA-PSS'
? { name: 'RSA-PSS', saltLength: 32 }
: key.algorithm.name === 'ECDSA'
? { name: 'ECDSA', hash: 'SHA-256' }
: { name: key.algorithm.name };
const signature = await window.crypto.subtle.sign(
params,
key,
dataBuffer
);
return arrayBufferToBase64(signature);
}
// Primary authentication function
async function authenticatedRequest<T>(
method: 'get' | 'post',
url: string,
data?: any
): Promise<T> {
debugLog('Auth Request', `${method.toUpperCase()} ${url}`, data ? { dataType: typeof data } : {});
try {
const token = await storage.authToken.load();
if (!token) throw new Error('Not authenticated');
// Ensure hardware key is ready
await initHardwareKey();
// Prepare request data
const timestamp = Date.now().toString();
const requestData = data ? JSON.stringify(data) : timestamp;
const headers: Record<string, string> = { 'Authorization': `Bearer ${token}` };
debugLog('Auth Request', `Using ${accelerationKeyId ? 'existing' : 'new'} acceleration key`);
// Handle different authentication methods based on available keys
if (accelerationKeyId) {
// Use existing acceleration key ID
await handleExistingKeyAuth(headers, requestData);
} else {
// Register new acceleration key
await handleNewKeyRegistration(headers, requestData);
}
// Make the authenticated request
const response = await apiClient.request<T>({
method,
url,
data,
headers
});
// Process response if this was a new key registration
if (!accelerationKeyId && response.headers['x-rpc-sec-bound-token-accel-pub-id']) {
const headers = Object.fromEntries(
Object.entries(response.headers).map(([key, value]) => [key, String(value)])
);
await processKeyRegistrationResponse(headers);
}
debugLog('Auth Request', 'Request completed successfully');
return response.data;
} catch (error) {
debugLog('Auth Request', 'Request failed', error);
if (axios.isAxiosError(error)) {
const axiosError = error as AxiosError<ServerResponse>;
if (axiosError.response?.data?.message) {
throw new Error(axiosError.response.data.message);
}
}
throw error;
}
}
// Helper for existing key authentication
async function handleExistingKeyAuth(headers: Record<string, string>, requestData: string): Promise<void> {
debugLog('Existing Auth', 'Setting up authentication with existing key', {
keyType: symmetricKey && preferSymmetricEncryption ? 'symmetric' : 'asymmetric',
dataLength: requestData.length,
accelerationKeyId
});
if (symmetricKey && preferSymmetricEncryption) {
// Use HMAC for authentication
debugLog('Existing Auth', 'Using HMAC authentication');
const hmac = await generateHMAC(symmetricKey, requestData);
debugLog('Existing Auth', `Generated HMAC signature: ${hmac.substring(0, 20)}...`);
headers['x-rpc-sec-bound-token-data'] = requestData;
headers['x-rpc-sec-bound-token-data-sig'] = hmac; // Unified header for signature
headers['x-rpc-sec-bound-token-accel-pub-id'] = accelerationKeyId!;
} else if (accelerationKey) {
// Use asymmetric signatures
debugLog('Existing Auth', 'Using asymmetric signature authentication');
const signature = await signWithKey(accelerationKey.privateKey, requestData);
debugLog('Existing Auth', `Generated signature: ${signature.substring(0, 20)}...`);
headers['x-rpc-sec-bound-token-data'] = requestData;
headers['x-rpc-sec-bound-token-data-sig'] = signature; // Unified header for signature
headers['x-rpc-sec-bound-token-accel-pub-id'] = accelerationKeyId!;
} else {
debugLog('Existing Auth', 'Invalid key state, forcing new registration');
accelerationKeyId = null;
throw new Error('Invalid key state, will register new key');
}
}
// Helper for new key registration
async function handleNewKeyRegistration(headers: Record<string, string>, requestData: string): Promise<void> {
debugLog('New Key Auth', 'Registering new acceleration key', {
preferSymmetric: preferSymmetricEncryption
});
let isEcdhGenerated = false;
// Try ECDH key exchange if supported and preferred
if (window.crypto.subtle && preferSymmetricEncryption) {
try {
// Setup ECDH key exchange
const { ecdhPubKeyBase64, ecdhPubKeySig } = await setupECDHAccelerationKey();
// Sign request data with hardware key for this first exchange
const dataSig = await signWithKey(hardwareKey!.privateKey, requestData);
headers['x-rpc-sec-bound-token-accel-pub'] = ecdhPubKeyBase64;
headers['x-rpc-sec-bound-token-accel-pub-type'] = 'ecdh';
headers['x-rpc-sec-bound-token-accel-pub-sig'] = ecdhPubKeySig;
headers['x-rpc-sec-bound-token-data'] = requestData;
headers['x-rpc-sec-bound-token-data-sig'] = dataSig;
isEcdhGenerated = true;
} catch (error) {
debugLog('New Key Auth', 'ECDH key exchange failed, falling back to asymmetric keys', error);
console.debug('ECDH key exchange failed, falling back to asymmetric keys', error);
}
}
// Fall back to asymmetric keys if ECDH isn't available or failed
if (!isEcdhGenerated) {
debugLog('New Key Auth', 'Using asymmetric key pair');
const { accelPubKeyBase64, accelPubKeySig, keyType } = await setupAccelerationKey();
const signature = await signWithKey(accelerationKey!.privateKey, requestData);
headers['x-rpc-sec-bound-token-accel-pub'] = accelPubKeyBase64;
headers['x-rpc-sec-bound-token-accel-pub-type'] = keyType;
headers['x-rpc-sec-bound-token-accel-pub-sig'] = accelPubKeySig;
headers['x-rpc-sec-bound-token-data'] = requestData;
headers['x-rpc-sec-bound-token-data-sig'] = signature;
}
debugLog('New Key Auth', 'New key registration headers set up');
}
// Process key registration response
async function processKeyRegistrationResponse(headers: Record<string, string>): Promise<void> {
debugLog('Key Registration', 'Processing key registration response', headers);
// Store the key ID
const keyId = headers['x-rpc-sec-bound-token-accel-pub-id'];
if (keyId) {
debugLog('Key Registration', `Received key ID: ${keyId}`);
accelerationKeyId = keyId;
// If this was an ECDH key exchange, process server's public key
const serverPubKey = headers['x-rpc-sec-bound-token-accel-pub'];
if (ecdhAccelerationKey && serverPubKey && preferSymmetricEncryption) {
debugLog('Key Registration', 'Processing ECDH server public key', {
publicKeyLength: serverPubKey.length
});
try {
// Derive the shared secret and create the HMAC key
symmetricKey = await deriveSharedKey(ecdhAccelerationKey.privateKey, serverPubKey);
debugLog('Key Registration', 'ECDH key exchange completed successfully');
console.debug('ECDH key exchange successful, HMAC authentication enabled');
} catch (error) {
debugLog('Key Registration', 'Failed to establish HMAC key', error);
console.error('Failed to establish HMAC key:', error);
}
}
} else {
debugLog('Key Registration', 'No acceleration key ID received');
}
}
// Public API functions
export async function toggleSymmetricEncryption(): Promise<boolean> {
debugLog('API', `Toggling symmetric encryption from ${preferSymmetricEncryption} to ${!preferSymmetricEncryption}`);
// Toggle the preference
preferSymmetricEncryption = !preferSymmetricEncryption;
// Store the updated preference
await storage.preferSymmetric.store(preferSymmetricEncryption);
// If disabling, clear the symmetric key (we'll keep using asymmetric with existing key ID)
if (!preferSymmetricEncryption) {
symmetricKey = null;
}
// Reset key state
accelerationKeyId = null;
debugLog('API', `Symmetric encryption set to ${preferSymmetricEncryption}`);
return preferSymmetricEncryption;
}
export function isSymmetricEncryptionEnabled(): boolean {
return preferSymmetricEncryption;
}
export async function register(userData: { username: string; password: string }) {
const response = await apiClient.post<ServerResponse>('/register', userData);
return response.data;
}
export async function login(credentials: { username: string; password: string }) {
debugLog('API', 'Login attempt', { username: credentials.username });
// Ensure hardware key is ready for login
await initHardwareKey();
// Get hardware public key
const hwPubKey = await exportPublicKey(hardwareKey!.publicKey);
const hwKeyType = hardwareKey!.publicKey.algorithm.name.toLowerCase();
debugLog('API', 'Hardware key prepared', {
keyType: hwKeyType,
publicKeyLength: hwPubKey.length
});
// Setup request with hardware key headers
const response = await apiClient.post<LoginResponse>(
'/login',
credentials,
{
headers: {
'x-rpc-sec-bound-token-hw-pub': hwPubKey,
'x-rpc-sec-bound-token-hw-pub-type': hwKeyType,
}
}
);
// Store the auth token
await storage.authToken.store(response.data.token);
// Clear any existing acceleration keys when logging in
accelerationKey = null;
accelerationKeyId = null;
ecdhAccelerationKey = null;
symmetricKey = null;
debugLog('API', 'Login successful');
return response.data;
}
export async function isAuthenticated(): Promise<boolean> {
debugLog('API', 'Checking authentication status');
try {
const token = await storage.authToken.load();
if (!token) return false;
// Make an authenticated request to verify the token is valid
const response = await authenticatedRequest<AuthResponse>('get', '/authenticated');
debugLog('API', `Authentication status: ${response.authenticated}`);
return response.authenticated;
} catch (error) {
debugLog('API', 'Authentication check failed', error);
console.debug('Authentication check failed:', error);
return false;
}
}
export function logout(): void {
debugLog('API', 'Logging out, clearing all keys and tokens');
Promise.all([
storage.authToken.delete(),
storage.hardwareKey.delete(),
]).catch(console.error);
// Clear all sensitive data from memory
hardwareKey = null;
accelerationKey = null;
accelerationKeyId = null;
ecdhAccelerationKey = null;
symmetricKey = null;
}
// Initialize the service on module load
init().catch(error => {
debugLog('Init', 'Service initialization failed', error);
console.error(error);
});
// Add window unload handler to clear sensitive keys from memory
if (typeof window !== 'undefined') {
window.addEventListener('beforeunload', () => {
ecdhAccelerationKey = null;
symmetricKey = null;
});
}

View File

@@ -0,0 +1,9 @@
/** @type {import('tailwindcss').Config} */
export default {
content: ["./index.html", "./src/**/*.{vue,js,ts,jsx,tsx}"],
darkMode: 'class',
theme: {
extend: {},
},
plugins: [],
};

View File

@@ -0,0 +1,12 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
"exclude": ["src/**/__tests__/*"],
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"paths": {
"@/*": ["./src/*"]
}
}
}

View File

@@ -0,0 +1,11 @@
{
"files": [],
"references": [
{
"path": "./tsconfig.node.json"
},
{
"path": "./tsconfig.app.json"
}
]
}

View File

@@ -0,0 +1,19 @@
{
"extends": "@tsconfig/node22/tsconfig.json",
"include": [
"vite.config.*",
"vitest.config.*",
"cypress.config.*",
"nightwatch.conf.*",
"playwright.config.*",
"eslint.config.*"
],
"compilerOptions": {
"noEmit": true,
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"module": "ESNext",
"moduleResolution": "Bundler",
"types": ["node"]
}
}

View File

@@ -0,0 +1,18 @@
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
// https://vite.dev/config/
export default defineConfig({
plugins: [
vue(),
vueDevTools(),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
},
},
})

7
hw-sign-go/go.mod Normal file
View File

@@ -0,0 +1,7 @@
module hw-sign-go
go 1.24.1
require (
github.com/patrickmn/go-cache v2.1.0+incompatible
)

6
hw-sign-go/go.sum Normal file
View File

@@ -0,0 +1,6 @@
github.com/btcsuite/btcd/btcec/v2 v2.3.2/go.mod h1:zYzJ8etWJQIv1Ogk7OzpWjowwOdXY1W/17j2MW85J04=
github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc=
github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeCxkaw7y45JueMRL4DIyJDKs=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=

1819
hw-sign-go/main.go Normal file

File diff suppressed because it is too large Load Diff

470
hw-sign-go/main_test.go Normal file
View File

@@ -0,0 +1,470 @@
package main
import (
"crypto/ecdh"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"fmt"
"testing"
"time"
)
// Test data structures
type TestData struct {
Timestamp string
RandHex string
Combined string
}
// Helper function to generate P-256 key pair (used for both hardware and acceleration keys)
func generateP256KeyPair() (*ecdsa.PrivateKey, *ecdsa.PublicKey, error) {
privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, nil, err
}
return privKey, &privKey.PublicKey, nil
}
// Helper function to generate test data
func generateTestData() *TestData {
timestamp := fmt.Sprintf("%d", time.Now().UnixNano())
randBytes := make([]byte, 16)
rand.Read(randBytes)
randHex := hex.EncodeToString(randBytes)
return &TestData{
Timestamp: timestamp,
RandHex: randHex,
Combined: timestamp + "-" + randHex,
}
}
// Single comprehensive benchmark test for the complete cryptographic workflow
func BenchmarkCompleteWorkflow(b *testing.B) {
b.Logf("Starting comprehensive cryptographic workflow benchmark")
for i := 0; i < b.N; i++ {
// Step 1: Prepare keys - create hw key pair (ecdsa-p256)
hwPriv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
b.Fatal("Failed to generate hardware key pair:", err)
}
hwPub := &hwPriv.PublicKey
// Step 1: Create accel key pair (P-256 for both signing and ECDH)
accelPriv, accelPub, err := generateP256KeyPair()
if err != nil {
b.Fatal("Failed to generate acceleration key pair:", err)
}
// Step 2: Sign accel pub by hw priv
accelPubBytes := elliptic.Marshal(elliptic.P256(), accelPub.X, accelPub.Y)
r, s, err := ecdsa.Sign(rand.Reader, hwPriv, accelPubBytes[:])
if err != nil {
b.Fatal("Failed to sign acceleration public key:", err)
}
// Step 3: Sign data (timestamp-randhex) by accel priv
testData := generateTestData()
dataHash := sha256.Sum256([]byte(testData.Combined))
dataR, dataS, err := ecdsa.Sign(rand.Reader, accelPriv, dataHash[:])
if err != nil {
b.Fatal("Failed to sign test data:", err)
}
// Step 4: Server verify accel pub by hw pub
if !ecdsa.Verify(hwPub, accelPubBytes[:], r, s) {
b.Fatal("Failed to verify acceleration public key signature")
}
// Step 5: Server verify data sig by accel pub
if !ecdsa.Verify(accelPub, dataHash[:], dataR, dataS) {
b.Fatal("Failed to verify data signature")
}
// Step 6: Create server ecdh-p256 key pair and do key exchange with accel pub
// Convert to ECDH format
accelPubECDHBytes := elliptic.Marshal(elliptic.P256(), accelPub.X, accelPub.Y)
curve := ecdh.P256()
clientECDHPub, err := curve.NewPublicKey(accelPubECDHBytes)
if err != nil {
b.Fatal("Failed to create client ECDH public key:", err)
}
// Generate server ECDH key pair
serverECDHPriv, err := curve.GenerateKey(rand.Reader)
if err != nil {
b.Fatal("Failed to generate server ECDH key pair:", err)
}
// Perform key exchange
sharedSecret, err := serverECDHPriv.ECDH(clientECDHPub)
if err != nil {
b.Fatal("Failed to perform ECDH key exchange:", err)
}
// Verify we got a valid shared secret
if len(sharedSecret) == 0 {
b.Fatal("Empty shared secret from ECDH")
}
// Log progress every 100 iterations for longer benchmarks
if (i+1)%100 == 0 {
b.Logf("Completed %d iterations successfully", i+1)
}
}
}
// Single comprehensive test for the complete cryptographic workflow
func TestCompleteWorkflow(t *testing.T) {
t.Logf("Starting comprehensive cryptographic workflow test")
// Step 1: Prepare keys - create hw key pair (ecdsa-p256)
t.Log("Step 1: Generating hardware key pair (ECDSA P-256)")
hwPriv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal("Failed to generate hardware key pair:", err)
}
hwPub := &hwPriv.PublicKey
t.Logf("Hardware P-256 public key: %s", base64.StdEncoding.EncodeToString(elliptic.Marshal(elliptic.P256(), hwPub.X, hwPub.Y)))
// Step 1: Create accel key pair (P-256 for both signing and ECDH)
t.Log("Step 1: Generating acceleration key pair (P-256)")
accelPriv, accelPub, err := generateP256KeyPair()
if err != nil {
t.Fatal("Failed to generate acceleration key pair:", err)
}
t.Logf("Acceleration P-256 public key: %s", base64.StdEncoding.EncodeToString(elliptic.Marshal(elliptic.P256(), accelPub.X, accelPub.Y)))
// Step 2: Sign accel pub by hw priv
t.Log("Step 2: Signing acceleration public key with hardware private key")
accelPubBytes := elliptic.Marshal(elliptic.P256(), accelPub.X, accelPub.Y)
accelPubHash := sha256.Sum256(accelPubBytes)
r, s, err := ecdsa.Sign(rand.Reader, hwPriv, accelPubHash[:])
if err != nil {
t.Fatal("Failed to sign acceleration public key:", err)
}
t.Logf("Acceleration public key signature: r=%s", r.String())
// Step 3: Sign data (timestamp-randhex) by accel priv
t.Log("Step 3: Generating test data and signing with acceleration private key")
testData := generateTestData()
t.Logf("Test data: %s", testData.Combined)
dataHash := sha256.Sum256([]byte(testData.Combined))
dataR, dataS, err := ecdsa.Sign(rand.Reader, accelPriv, dataHash[:])
if err != nil {
t.Fatal("Failed to sign test data:", err)
}
t.Logf("Data signature created successfully")
// Step 4: Server verify accel pub by hw pub
t.Log("Step 4: Server verifying acceleration public key signature")
if !ecdsa.Verify(hwPub, accelPubHash[:], r, s) {
t.Fatal("Failed to verify acceleration public key signature")
}
t.Log("✓ Acceleration public key signature verified successfully")
// Step 5: Server verify data sig by accel pub
t.Log("Step 5: Server verifying data signature")
if !ecdsa.Verify(accelPub, dataHash[:], dataR, dataS) {
t.Fatal("Failed to verify data signature")
}
t.Log("✓ Data signature verified successfully")
// Step 6: Create server ecdh-p256 key pair and do key exchange with accel pub
t.Log("Step 6: Performing ECDH key exchange")
// Convert to ECDH format
accelPubECDHBytes := elliptic.Marshal(elliptic.P256(), accelPub.X, accelPub.Y)
curve := ecdh.P256()
clientECDHPub, err := curve.NewPublicKey(accelPubECDHBytes)
if err != nil {
t.Fatal("Failed to create client ECDH public key:", err)
}
// Generate server ECDH key pair
serverECDHPriv, err := curve.GenerateKey(rand.Reader)
if err != nil {
t.Fatal("Failed to generate server ECDH key pair:", err)
}
serverECDHPub, _ := x509.MarshalPKIXPublicKey(serverECDHPriv.PublicKey())
t.Logf("Server ECDH public key: %s", base64.StdEncoding.EncodeToString(serverECDHPub))
// Perform key exchange
sharedSecret, err := serverECDHPriv.ECDH(clientECDHPub)
if err != nil {
t.Fatal("Failed to perform ECDH key exchange:", err)
}
// Verify we got a valid shared secret
if len(sharedSecret) == 0 {
t.Fatal("Empty shared secret from ECDH")
}
t.Logf("✓ ECDH key exchange successful! Shared secret length: %d bytes", len(sharedSecret))
t.Logf("Shared secret: %s", base64.StdEncoding.EncodeToString(sharedSecret))
t.Log("🎉 Complete cryptographic workflow test passed successfully!")
}
// Performance comparison test
func TestPerformanceComparison(t *testing.T) {
const iterations = 100
t.Run("P256Operations", func(t *testing.T) {
// Time key generation
start := time.Now()
for i := 0; i < iterations; i++ {
_, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
}
keyGenDuration := time.Since(start)
// Time signing operations
hwPriv, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
testData := []byte("performance test data")
hash := sha256.Sum256(testData)
start = time.Now()
for i := 0; i < iterations; i++ {
_, _, err := ecdsa.Sign(rand.Reader, hwPriv, hash[:])
if err != nil {
t.Fatal(err)
}
}
signDuration := time.Since(start)
// Time verification operations
r, s, _ := ecdsa.Sign(rand.Reader, hwPriv, hash[:])
start = time.Now()
for i := 0; i < iterations; i++ {
if !ecdsa.Verify(&hwPriv.PublicKey, hash[:], r, s) {
t.Fatal("verification failed")
}
}
verifyDuration := time.Since(start)
// Time ECDH operations
curve := ecdh.P256()
start = time.Now()
for i := 0; i < iterations; i++ {
priv1, _ := curve.GenerateKey(rand.Reader)
priv2, _ := curve.GenerateKey(rand.Reader)
_, err := priv1.ECDH(priv2.PublicKey())
if err != nil {
t.Fatal(err)
}
}
ecdhDuration := time.Since(start)
// Report results
t.Logf("P-256 Performance Results (%d iterations):", iterations)
t.Logf("Key generation: %v (avg: %v)", keyGenDuration, keyGenDuration/iterations)
t.Logf("Signing: %v (avg: %v)", signDuration, signDuration/iterations)
t.Logf("Verification: %v (avg: %v)", verifyDuration, verifyDuration/iterations)
t.Logf("ECDH: %v (avg: %v)", ecdhDuration, ecdhDuration/iterations)
})
}
// Test ECDSA P-256 signature verification with provided test data
func TestECDSAP256SignatureVerification(t *testing.T) {
t.Log("Testing ECDSA P-256 signature verification with provided test data")
// Test data sets
testCases := []struct {
name string
publicKeyB64 string
plaintextB64 string
signatures []string
}{
{
name: "Windows",
publicKeyB64: "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEs7QlaLpB0jw6DQvyLyDtOqzvrrjHvrKqAnys6qgGyqozpku3tS/gwvcKNBDifyr05UYHYAcLzyLNJ57XYkPPiw==",
plaintextB64: "1234567890==",
signatures: []string{
"YLvs+xya4PZU2/jz8saWk/tPlja4B9mkz6iDAHf1OfsMZDhtThpP5JMCtJociPp/sZGHq/4+LF5ndR4DYeCD6A==",
"Mvm0l6My9Cz8wXea8XFuRTNqYpDQuu+1qNzJyyoOI/WFwYsm/782HyHC4OOanZYtCtK2yUuFEUhvrHC8UA37rA==",
"1BYuwr05K8BC9YYScWwUSrQac71cmnj8so8Auukt2XiNm6o5R/ZauVdlzdCovLu9Y1EFYtfM4Ij0wSatXqMOcA==",
"YFfguSt6i6zUZwiRGKfJeFoDeDa6ZZ2Iknx0NUBNjyX054MJFr/IolsyDUefv+206y8VRk+3vPFcdJBre3K76Q==",
},
},
{
name: "macOS",
publicKeyB64: "BJQ+7eXZcgPnI5P73nGlsgn3RCY1yLEhdA3KJNnrUbniC0LaSlUtMpaBhzeQjgRYZYi4wPSVfLJZ9T8Ao5CRai8=",
plaintextB64: "1234567890==",
signatures: []string{
"MEUCIQDfWzCdfE50ZM/HsfO55PHIgqR5C+jg1WiwK1HVHLlSRQIgDnG2Xxhr4S+SWlHNWHgzaxeMVV02xjiLMlh6qAJFwJ0=",
"MEUCIHQMI9V89fSU9leOGQLr7cCTY56Vuc44OkxpLVWZUmojAiEAtcrJp7E50Id6SdEqFVtstjUp+rpZSpu3Vzhgwff94+E=",
"MEUCIFzPM6VC8fzEEX5wcq8D+LOQirjg1lDq7qqbo+i0P+dMAiEA4Spe3bGJdyTUGumjhc/Qosh9TDQnRkWQ9c0S2GwEFbA=",
},
},
{
name: "Test3",
publicKeyB64: "BGD4KpyqndHf5CTpAlZXTubZXaaoqac4LJ0QNUlS8rWjOwh8frmZTsAD1C6ps5iB5aZt5lc/X8LGgMu0334plGg=",
plaintextB64: "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEigUJp7M4QumQ7r+xgsQqgNCsxFVaOz30EslGdi+lmN0DcX7RKAHCldU96JRj4A/AKxYOeN/Fb7VdVb7Wy1w3dg==",
signatures: []string{
"MEYCIQDA5DNoHDj5vX6pvtxRcu8HJnB4sDE7tMvOkKz+F8roGAIhAPzSWhOtE4sT3nCF7rcH0SQXmGWwHbCgplOOnnQh+EmP",
},
},
}
for _, testCase := range testCases {
t.Logf("Testing %s", testCase.name)
// Parse the public key
t.Logf("Step 1: Parsing ECDSA P-256 public key for %s", testCase.name)
// Handle different key formats
var publicKey interface{}
var err error
// Try parsing as standard PKIX first
publicKey, err = parsePublicKey(testCase.publicKeyB64, "ecdsa-p256")
if err != nil {
// If PKIX parsing fails, try raw point format (second test case)
t.Errorf("PKIX parsing failed, trying raw point format: %v", err)
return
}
ecdsaKey, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
t.Fatal("Parsed key is not ECDSA")
}
// Verify the curve
if ecdsaKey.Curve != elliptic.P256() {
t.Fatal("Key is not P-256 curve")
}
t.Logf("✓ Successfully parsed ECDSA P-256 public key for %s", testCase.name)
// Test signature verification
t.Logf("Step 2: Testing signature verification for %s", testCase.name)
successCount := 0
for i, sigB64 := range testCase.signatures {
t.Logf("Testing signature %d: %s", i+1, sigB64)
// Test using the main verifySignature function
sigBytes, err := base64.StdEncoding.DecodeString(sigB64)
if err != nil {
t.Errorf("Signature %d: Failed to decode signature: %v", i+1, err)
continue
}
// Test using the main verifySignature function
plainBytes, err := base64.StdEncoding.DecodeString(testCase.plaintextB64)
if err != nil {
t.Errorf("Signature %d: Failed to decode plaintextB64: %v", i+1, err)
continue
}
// Verify using the main verifySignature function
isValid := verifySignature(ecdsaKey, plainBytes, sigBytes)
if isValid {
t.Logf("✓ Signature %d verified successfully using verifySignature()", i+1)
successCount++
} else {
t.Logf("✗ Signature %d failed verification using verifySignature()", i+1)
}
}
t.Logf("Verification complete for %s: %d/%d signatures verified successfully", testCase.name, successCount, len(testCase.signatures))
if successCount == 0 {
t.Errorf("No signatures were successfully verified for %s - this may indicate a format issue", testCase.name)
}
t.Log("---")
}
}
// Test RSA-2048 PSS signature verification with provided test data
func TestRSA2048PSSSignatureVerification(t *testing.T) {
t.Log("Testing RSA-2048 PSS signature verification with provided test data")
// Test data sets
testCases := []struct {
name string
publicKeyB64 string
plaintextB64 string
signatures []string
}{
{
name: "Windows",
publicKeyB64: "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3n0ussUHvZhH1nBZiWEka3OL6OFo7P+jXn+oaOkG+mloxG7JMmnp943z/z5rWvUNN6kZz2ZZeQ+k+ezBZKKvvI+n4ZP5IkgJ/I1nPJzRLKb79OgZATm4Bo/hhQIDdmcsHid7Ajmh+9PoqUwOcX/pZ6FFdSvw/cQc2SB38b5ghpCx3dpUrAfZUV1U3eC1uUr7KiyRm8Dj1hPg4ri9jJhqB4ktr0FjLF43kUlBmZzoNsKq9WcxukF/aLAAgYBBC/d0/FIBRemAgLWJWNm5j45aE0dmKFLfoz2hH4TG4mXKNljbc6O0dQUnM+xMkmhC5FrAXOo3YtZw8ooaVeALPjBCWwIDAQAB",
plaintextB64: "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEiH3HbpFLTj27XqObpHeJKXW6j3TTwhX2o2LAheAmtBQU/Qgn/4DTeMlRh0tweqFno1QLhQ2Nu4QlpqmsiegscQ==",
signatures: []string{
"eKpBcP5DFWEMONxKk8iAyb5pabBppZVgBBT2Ftm9OmtQkh+bCPLGJM6ILVi6Tg3VafbBFPjwNERXSwfXbUsiP6ca8ijXKp7aWYdBu4gtRVbzoj6gr47jo3A38cMbfcm7AEpQfboovT6f0wUPXfnN2vEocprJM8vZ/BC3fmjNL8R5m3+QRY+y9b3Mu8zCr/rTLw8aflz7b7r2Nb+a2kkFLgdk1tgJTz+/gUTU/N+txVDyjFcdhWLY18p96D0PDVCgvYXIFstbF+VVZVSTAOSlg1QCP/JCEgMWrt1/cLimLr8hFXv0kAL2x4/V7C6KkZk7Z7BFxQbP76lpXtp5rTJnZw==",
},
},
}
for _, testCase := range testCases {
t.Logf("Testing %s", testCase.name)
// Parse the public key
t.Logf("Step 1: Parsing RSA-2048 PSS public key for %s", testCase.name)
// Handle different key formats
var publicKey interface{}
var err error
// Try parsing as standard PKIX first
publicKey, err = parsePublicKey(testCase.publicKeyB64, "rsa-2048-pss")
if err != nil {
// If PKIX parsing fails, try raw point format (second test case)
t.Errorf("PKIX parsing failed, trying raw point format: %v", err)
return
}
rsaKey, ok := publicKey.(*rsa.PublicKey)
if !ok {
t.Fatal("Parsed key is not RSA")
}
// Test signature verification
t.Logf("Step 2: Testing signature verification for %s", testCase.name)
successCount := 0
for i, sigB64 := range testCase.signatures {
t.Logf("Testing signature %d: %s", i+1, sigB64)
// Test using the main verifySignature function
sigBytes, err := base64.StdEncoding.DecodeString(sigB64)
if err != nil {
t.Errorf("Signature %d: Failed to decode signature: %v", i+1, err)
continue
}
// Test using the main verifySignature function
plainBytes, err := base64.StdEncoding.DecodeString(testCase.plaintextB64)
if err != nil {
t.Errorf("Signature %d: Failed to decode plaintextB64: %v", i+1, err)
continue
}
// Verify using the main verifySignature function
isValid := verifySignature(rsaKey, plainBytes, sigBytes)
if isValid {
t.Logf("✓ Signature %d verified successfully using verifySignature()", i+1)
successCount++
} else {
t.Logf("✗ Signature %d failed verification using verifySignature()", i+1)
}
}
t.Logf("Verification complete for %s: %d/%d signatures verified successfully", testCase.name, successCount, len(testCase.signatures))
if successCount == 0 {
t.Errorf("No signatures were successfully verified for %s - this may indicate a format issue", testCase.name)
}
t.Log("---")
}
}

View File

@@ -0,0 +1,543 @@
#!/usr/bin/env python3
import base64
import json
import os
import time
import hmac
import hashlib
from dataclasses import dataclass, field, asdict
from typing import Dict, List, Optional, Any, Tuple
import secrets
import uuid
# For cryptographic operations
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec, utils
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.backends import default_backend
@dataclass
class KeyConfig:
"""Configuration for key storage."""
file_path: str = "hw_sign_keys.json"
hardware_key_type: str = "ecdsa-p256" # Options: ecdsa-p256, ed25519, rsa-2048
accel_key_type: str = "ecdh-p256" # Options: ecdh-p256, ecdsa-p256, rsa-2048
@dataclass
class KeyPair:
"""Represents a key pair with additional metadata."""
id: str
key_type: str
created_at: int
private_key: Optional[str] = None # Base64 encoded private key
public_key: Optional[str] = None # Base64 encoded public key
@dataclass
class SharedSecret:
"""Represents a shared secret derived from ECDH."""
id: str
secret: str # Base64 encoded shared secret
client_pub_key: str # Client's public key used in derivation
server_pub_key: str # Server's public key used in derivation
created_at: int
expires_at: Optional[int] = None
@dataclass
class KeyStorage:
"""Storage for all keys and shared secrets."""
hardware_keys: List[KeyPair] = field(default_factory=list)
accel_keys: List[KeyPair] = field(default_factory=list)
shared_secrets: List[SharedSecret] = field(default_factory=list)
class HwSignMock:
"""Mock implementation of hardware-bound signing."""
def __init__(self, config: KeyConfig = None):
"""Initialize with optional configuration."""
self.config = config or KeyConfig()
self.storage = self._load_storage()
self.current_hw_key: Optional[KeyPair] = None
self.current_accel_key: Optional[KeyPair] = None
self.current_shared_secret: Optional[SharedSecret] = None
# Initialize keys if none exist
if not self.storage.hardware_keys:
self._generate_hardware_key()
# Set current hardware key
self.current_hw_key = self.storage.hardware_keys[-1]
print(f"Initialized HW Sign Mock with {len(self.storage.hardware_keys)} hardware keys")
def _load_storage(self) -> KeyStorage:
"""Load key storage from file or create new storage."""
try:
if os.path.exists(self.config.file_path):
with open(self.config.file_path, 'r') as f:
data = json.load(f)
storage = KeyStorage(
hardware_keys=[KeyPair(**k) for k in data.get('hardware_keys', [])],
accel_keys=[KeyPair(**k) for k in data.get('accel_keys', [])],
shared_secrets=[SharedSecret(**s) for s in data.get('shared_secrets', [])]
)
print(f"Loaded {len(storage.hardware_keys)} hardware keys from {self.config.file_path}")
return storage
except Exception as e:
print(f"Error loading key storage: {e}")
# Return empty storage if file doesn't exist or has errors
return KeyStorage()
def _save_storage(self):
"""Save key storage to file."""
# Convert to dictionary
data = {
"hardware_keys": [asdict(k) for k in self.storage.hardware_keys],
"accel_keys": [asdict(k) for k in self.storage.accel_keys],
"shared_secrets": [asdict(s) for s in self.storage.shared_secrets]
}
# Save to file
with open(self.config.file_path, 'w') as f:
json.dump(data, f, indent=2)
print(f"Saved key storage to {self.config.file_path}")
def _generate_hardware_key(self) -> KeyPair:
"""Generate a new hardware key pair."""
key_id = str(uuid.uuid4())
created_at = int(time.time())
# Generate EC key pair
if self.config.hardware_key_type == "ecdsa-p256":
private_key = ec.generate_private_key(
ec.SECP256R1(), # P-256 curve
default_backend()
)
# Serialize keys
private_bytes = private_key.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
public_bytes = private_key.public_key().public_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
else:
raise ValueError(f"Unsupported hardware key type: {self.config.hardware_key_type}")
# Create key pair
key_pair = KeyPair(
id=key_id,
key_type=self.config.hardware_key_type,
created_at=created_at,
private_key=base64.b64encode(private_bytes).decode('utf-8'),
public_key=base64.b64encode(public_bytes).decode('utf-8')
)
# Add to storage
self.storage.hardware_keys.append(key_pair)
self._save_storage()
print(f"Generated new hardware key of type {self.config.hardware_key_type} with ID {key_id}")
return key_pair
def _generate_accel_key(self) -> KeyPair:
"""Generate a new acceleration key pair."""
key_id = str(uuid.uuid4())
created_at = int(time.time())
# Generate EC key pair for ECDH
if self.config.accel_key_type == "ecdh-p256":
private_key = ec.generate_private_key(
ec.SECP256R1(), # P-256 curve
default_backend()
)
# Serialize keys
private_bytes = private_key.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
public_bytes = private_key.public_key().public_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
else:
raise ValueError(f"Unsupported acceleration key type: {self.config.accel_key_type}")
# Create key pair
key_pair = KeyPair(
id=key_id,
key_type=self.config.accel_key_type,
created_at=created_at,
private_key=base64.b64encode(private_bytes).decode('utf-8'),
public_key=base64.b64encode(public_bytes).decode('utf-8')
)
# Add to storage
self.storage.accel_keys.append(key_pair)
self._save_storage()
print(f"Generated new acceleration key of type {self.config.accel_key_type} with ID {key_id}")
return key_pair
def _load_private_key(self, key_pair: KeyPair):
"""Load private key from key pair."""
if not key_pair or not key_pair.private_key:
raise ValueError("Invalid key pair")
private_bytes = base64.b64decode(key_pair.private_key)
if key_pair.key_type == "ecdsa-p256" or key_pair.key_type == "ecdh-p256":
return serialization.load_der_private_key(
private_bytes,
password=None,
backend=default_backend()
)
else:
raise ValueError(f"Unsupported key type: {key_pair.key_type}")
def _load_public_key(self, base64_key: str, key_type: str = "ecdsa-p256"):
"""Load public key from base64 encoded string."""
public_bytes = base64.b64decode(base64_key)
if key_type == "ecdsa-p256" or key_type == "ecdh-p256":
return serialization.load_der_public_key(
public_bytes,
backend=default_backend()
)
else:
raise ValueError(f"Unsupported key type: {key_type}")
def sign_with_hardware_key(self, data: str) -> str:
"""Sign data with hardware key using ECDSA."""
if not self.current_hw_key:
raise ValueError("No hardware key available")
private_key = self._load_private_key(self.current_hw_key)
if self.current_hw_key.key_type == "ecdsa-p256":
# Sign using ECDSA
signature = private_key.sign(
data.encode('utf-8'),
ec.ECDSA(hashes.SHA256())
)
return base64.b64encode(signature).decode('utf-8')
else:
raise ValueError(f"Unsupported key type for signing: {self.current_hw_key.key_type}")
def sign_with_accel_key(self, data: str) -> str:
"""
Sign data with acceleration key.
If a shared secret exists, use HMAC-SHA256, otherwise use ECDSA.
"""
if self.current_shared_secret:
# Use HMAC with shared secret
return self._sign_hmac(data, self.current_shared_secret.secret)
# No shared secret, generate a new acceleration key if needed
if not self.current_accel_key:
self.current_accel_key = self._generate_accel_key()
private_key = self._load_private_key(self.current_accel_key)
if self.current_accel_key.key_type == "ecdh-p256":
# Sign using ECDSA (same operation as P-256 ECDSA)
signature = private_key.sign(
data.encode('utf-8'),
ec.ECDSA(hashes.SHA256())
)
return base64.b64encode(signature).decode('utf-8')
else:
raise ValueError(f"Unsupported key type for signing: {self.current_accel_key.key_type}")
def _sign_hmac(self, data: str, secret_base64: str) -> str:
"""Sign data using HMAC-SHA256 with the shared secret."""
secret_bytes = base64.b64decode(secret_base64)
# Create HMAC
h = hmac.new(secret_bytes, data.encode('utf-8'), hashlib.sha256)
return base64.b64encode(h.digest()).decode('utf-8')
def get_hardware_public_key(self) -> Tuple[str, str]:
"""Get the current hardware public key and its type."""
if not self.current_hw_key:
self.current_hw_key = self._generate_hardware_key()
return self.current_hw_key.public_key, self.current_hw_key.key_type
def get_accel_public_key(self) -> Tuple[str, str]:
"""Get the current acceleration public key and its type."""
if not self.current_accel_key:
self.current_accel_key = self._generate_accel_key()
return self.current_accel_key.public_key, self.current_accel_key.key_type
def get_signed_accel_key(self) -> Tuple[str, str, str]:
"""
Get the acceleration public key, its type, and a signature of the public key
using the hardware key.
"""
if not self.current_accel_key:
self.current_accel_key = self._generate_accel_key()
# Sign the acceleration public key with the hardware key
signature = self.sign_with_hardware_key(self.current_accel_key.public_key)
return (
self.current_accel_key.public_key,
self.current_accel_key.key_type,
signature
)
def set_server_public_key(self, server_pub_key: str, key_id: str = None) -> str:
"""
Use the server's public key to establish a shared secret via ECDH.
Returns the ID of the established shared secret.
"""
if not self.current_accel_key:
self.current_accel_key = self._generate_accel_key()
# Load the client's private key
client_private_key = self._load_private_key(self.current_accel_key)
# Load the server's public key
try:
server_public_key = self._load_public_key(server_pub_key, "ecdh-p256")
# Perform key exchange
shared_key = client_private_key.exchange(ec.ECDH(), server_public_key)
# Derive final shared secret using HKDF
shared_secret = HKDF(
algorithm=hashes.SHA256(),
length=32,
salt=None,
info=b'hw-sign-ecdh',
backend=default_backend()
).derive(shared_key)
# Create shared secret entry
secret_id = key_id or str(uuid.uuid4())
shared_secret_entry = SharedSecret(
id=secret_id,
secret=base64.b64encode(shared_secret).decode('utf-8'),
client_pub_key=self.current_accel_key.public_key,
server_pub_key=server_pub_key,
created_at=int(time.time()),
expires_at=int(time.time()) + 3600 # 1 hour expiry
)
# Add to storage
self.storage.shared_secrets.append(shared_secret_entry)
self._save_storage()
# Set as current shared secret
self.current_shared_secret = shared_secret_entry
print(f"ECDH key exchange completed successfully. Secret ID: {secret_id}")
return secret_id
except Exception as e:
print(f"Error during ECDH key exchange: {e}")
raise
def generate_request_data(self) -> str:
"""Generate request data in the format: Timestamp-RandomHex."""
timestamp = str(int(time.time()))
random_hex = secrets.token_hex(16) # 32 bytes of hex
return f"{timestamp}-{random_hex}"
class TestClient:
"""Client for testing the hardware-bound authentication."""
def __init__(self, base_url: str = "http://localhost:28280"):
self.base_url = base_url
self.hw_sign = HwSignMock()
self.auth_token = None
self.accel_key_id = None
print(f"Initialized test client with base URL: {base_url}")
def test_register(self, username: str, password: str) -> bool:
"""Test user registration."""
print("\n=== Testing Registration (Simulated) ===")
print(f"Username: {username}")
print(f"Password: {password}")
# Simulate successful registration
print("✓ Registration successful!")
return True
def test_login(self, username: str, password: str) -> bool:
"""Test login with hardware key binding."""
print("\n=== Testing Login (Simulated) ===")
print(f"Username: {username}")
print(f"Password: {password}")
# Get hardware public key
hw_pub_key, hw_pub_type = self.hw_sign.get_hardware_public_key()
print(f"Hardware public key (first 50 chars): {hw_pub_key[:50]}...")
print(f"Hardware key type: {hw_pub_type}")
# Simulate successful login
self.auth_token = f"mock_token_{secrets.token_hex(8)}"
print(f"✓ Login successful! Token: {self.auth_token[:20]}...")
return True
def test_authenticated(self) -> bool:
"""
Test authenticated request.
First request registers a new ECDH acceleration key.
Subsequent requests use the established shared secret.
"""
print("\n=== Testing Authenticated Request ===")
if not self.auth_token:
print("✗ No auth token available!")
return False
# Generate request timestamp
timestamp = self.hw_sign.generate_request_data()
print(f"Request timestamp: {timestamp}")
# Build request headers
headers = {
"Authorization": f"Bearer {self.auth_token}",
"x-rpc-sec-bound-token-data": timestamp
}
if not self.accel_key_id:
# First authenticated request - register ECDH acceleration key
print("Registering new ECDH acceleration key...")
# Get acceleration key and sign it with hardware key
accel_pub, accel_pub_type, accel_pub_sig = self.hw_sign.get_signed_accel_key()
# Sign the request data with acceleration key
data_sig = self.hw_sign.sign_with_accel_key(timestamp)
# Add headers
headers.update({
"x-rpc-sec-bound-token-accel-pub": accel_pub,
"x-rpc-sec-bound-token-accel-pub-type": accel_pub_type,
"x-rpc-sec-bound-token-accel-pub-sig": accel_pub_sig,
"x-rpc-sec-bound-token-data-sig": data_sig
})
print(f"Acceleration public key (first 50 chars): {accel_pub[:50]}...")
print(f"Acceleration key type: {accel_pub_type}")
print(f"Accel pub signature (first 20 chars): {accel_pub_sig[:20]}...")
print(f"Data signature (first 20 chars): {data_sig[:20]}...")
# Simulate server response
self.accel_key_id = f"accel_{secrets.token_hex(8)}"
server_pub_key = self._simulate_server_response()
# Establish shared secret
if server_pub_key:
self.hw_sign.set_server_public_key(server_pub_key, self.accel_key_id)
print(f"Received acceleration key ID: {self.accel_key_id}")
print(f"Received server ECDH public key: {server_pub_key[:30]}...")
print("Shared secret established for HMAC authentication")
else:
# Subsequent requests - use HMAC with shared secret
print(f"Using existing acceleration key ID with HMAC: {self.accel_key_id}")
# Sign data using HMAC with shared secret
data_sig = self.hw_sign.sign_with_accel_key(timestamp)
# Add headers
headers.update({
"x-rpc-sec-bound-token-accel-pub-id": self.accel_key_id,
"x-rpc-sec-bound-token-data-sig": data_sig
})
print(f"HMAC signature (first 20 chars): {data_sig[:20]}...")
# Simulate successful request
print("✓ Authenticated request successful!")
return True
def _simulate_server_response(self) -> str:
"""Simulate server response with a new ECDH public key."""
# Generate a mock server key
mock_server = HwSignMock()
server_pub_key, _ = mock_server.get_accel_public_key()
return server_pub_key
def run_full_test(self):
"""Run a full test sequence."""
print("=====================================")
print("Hardware-Bound Authentication Test")
print("ECDSA Hardware Key + ECDH Accel Key")
print("=====================================")
username = f"testuser_{int(time.time())}"
password = "testpass123"
# Test 1: Register
register_success = self.test_register(username, password)
# Test 2: Login with ECDSA hardware key
login_success = False
if register_success:
login_success = self.test_login(username, password)
# Test 3: Authenticated request (first time - register ECDH accel key)
auth_success1 = False
if login_success:
auth_success1 = self.test_authenticated()
# Test 4: Authenticated request (second time - use existing ECDH key)
auth_success2 = False
if auth_success1:
print("\n=== Testing Second Authenticated Request ===")
auth_success2 = self.test_authenticated()
# Test 5: Third authenticated request to verify ECDH key persistence
auth_success3 = False
if auth_success2:
print("\n=== Testing Third Authenticated Request ===")
auth_success3 = self.test_authenticated()
# Summary
print("\n=====================================")
print("Test Results Summary:")
print("=====================================")
print(f"Registration: {'✓ PASS' if register_success else '✗ FAIL'}")
print(f"Login (ECDSA HW key): {'✓ PASS' if login_success else '✗ FAIL'}")
print(f"Auth (new ECDH key): {'✓ PASS' if auth_success1 else '✗ FAIL'}")
print(f"Auth (existing ECDH): {'✓ PASS' if auth_success2 else '✗ FAIL'}")
print(f"Auth (ECDH persistent): {'✓ PASS' if auth_success3 else '✗ FAIL'}")
all_passed = register_success and login_success and auth_success1 and auth_success2 and auth_success3
print(f"\nOverall Result: {'✓ ALL TESTS PASSED' if all_passed else '✗ SOME TESTS FAILED'}")
if all_passed:
print("\n🎉 Congratulations! All hardware-bound authentication tests passed!")
print("✓ ECDSA hardware key authentication works")
print("✓ ECDH acceleration key exchange works")
print("✓ Key persistence and reuse works")
print("=====================================")
if __name__ == "__main__":
client = TestClient()
client.run_full_test()

1
hw-sign-win/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
cmake-*/

View File

@@ -0,0 +1,43 @@
cmake_minimum_required(VERSION 3.15)
project(hw_sign_win)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Include vcpkg toolchain
set(CMAKE_TOOLCHAIN_FILE "${CMAKE_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake")
# Find dependencies
find_package(cpr CONFIG REQUIRED)
find_package(nlohmann_json CONFIG REQUIRED)
find_package(OpenSSL REQUIRED)
# Use pre-built TpmAtt library from TSS.MSR submodule
add_library(TpmAtt SHARED IMPORTED)
# Set properties for imported library
set_target_properties(TpmAtt PROPERTIES
IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/TSS.MSR/PCPTool.v11/x64/Debug/TpmAtt.dll"
IMPORTED_IMPLIB "${CMAKE_CURRENT_SOURCE_DIR}/TSS.MSR/PCPTool.v11/x64/Debug/TpmAtt.lib"
INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/TSS.MSR/PCPTool.v11/inc"
)
# Add main executable
add_executable(hw_sign_win main.cpp)
# Copy the DLL to the output directory
add_custom_command(TARGET hw_sign_win POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
"${CMAKE_CURRENT_SOURCE_DIR}/TSS.MSR/PCPTool.v11/x64/Debug/TpmAtt.dll"
$<TARGET_FILE_DIR:hw_sign_win>
)
# Link libraries to main executable
target_link_libraries(hw_sign_win PRIVATE
cpr::cpr
nlohmann_json::nlohmann_json
bcrypt
OpenSSL::SSL
OpenSSL::Crypto
TpmAtt # Link the TpmAtt library
)

1426
hw-sign-win/main.cpp Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1 @@
set(CMAKE_TOOLCHAIN_FILE "$ENV{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake" CACHE STRING "Vcpkg toolchain file")

9
hw-sign-win/vcpkg.json Normal file
View File

@@ -0,0 +1,9 @@
{
"name": "hw-sign-win",
"version": "1.0.0",
"dependencies": [
"cpr",
"nlohmann-json",
"openssl"
]
}