Encrypted packets are working in Linux. DOS is hanging for some reason.

This commit is contained in:
Scott Duensing 2021-12-07 20:20:05 -06:00
parent 859acf612b
commit 9c0c7b712d
38 changed files with 3300 additions and 2988 deletions

25
LICENSE
View file

@ -22,11 +22,6 @@ Licenses Used By:
Client
======
blowfish-api
------------
https://github.com/tombonner/blowfish-api
Attribution
DOS Serial Library
------------------
https://github.com/kstenerud/DOS-Serial-Library
@ -67,6 +62,16 @@ stb_image.h
https://github.com/nothings/stb
Public Domain
tiny-AES-c
----------
https://github.com/kokke/tiny-AES-c
Unlicense
tiny-AES128-C
-------------
https://github.com/bonybrown/tiny-AES128-C
Unlicense
Font Converter
==============
@ -104,3 +109,13 @@ stb_ds.h
--------
https://github.com/nothings/stb
Public Domain
tiny-AES-c
----------
https://github.com/kokke/tiny-AES-c
Unlicense
tiny-AES128-C
-------------
https://github.com/bonybrown/tiny-AES128-C
Unlicense

View file

@ -26,7 +26,9 @@ mkdir -p \
obj/client/src/thirdparty/serial \
obj/shared/thirdparty/memwatch \
obj/shared/thirdparty/blowfish-api \
obj/shared/thirdparty/ini/src
obj/shared/thirdparty/ini/src \
obj/shared/thirdparty/tiny-AES-c \
obj/shared/thirdparty/tiny-AES128-C
source /opt/cross/djgpp/setenv

View file

@ -58,10 +58,12 @@ HEADERS = \
$$SHARED/thirdparty/stb_ds.h \
$$SHARED/thirdparty/stb_image.h \
$$SHARED/thirdparty/memwatch/memwatch.h \
$$SHARED/thirdparty/blowfish-api/blowfish.h \
$$SHARED/thirdparty/ini/src/ini.h \
$$SHARED/thirdparty/tiny-AES-c/aes.h \
$$SHARED/thirdparty/tiny-AES128-C/pkcs7_padding.h \
$$SHARED/primes.h \
$$SHARED/packet.h \
$$SHARED/packets.h \
src/config.h \
$$SHARED/util.h \
src/gui/msgbox.h \
@ -102,9 +104,10 @@ HEADERS = \
SOURCES = \
$$LINUX_SOURCES \
$$SHARED/thirdparty/memwatch/memwatch.c \
$$SHARED/thirdparty/blowfish-api/blowfish.c \
$$SHARED/thirdparty/ini/src/ini.c \
$$SHARED/packet.c \
$$SHARED/thirdparty/tiny-AES-c/aes.c \
$$SHARED/thirdparty/tiny-AES128-C/pkcs7_padding.c \
src/config.c \
$$SHARED/memory.c \
src/gui/msgbox.c \

View file

@ -136,10 +136,22 @@ static void taskComDebugLoop(void *data) {
logWrite("Unexpected packet type received %d\n", decoded.packetType);
}
}
} else {
taskYield();
}
taskYield();
}
}
// Send LOGIN.
logWrite("Sending LOGIN\n");
PacketTypeLoginT loginData;
strcpy(loginData.user, "Encryption");
strcpy(loginData.pass, "Works!");
encoded.control = PACKET_CONTROL_DAT;
encoded.packetType = PACKET_TYPE_LOGIN;
encoded.channel = 1;
encoded.encrypt = 1;
packetEncode(__packetThreadData, &encoded, (char *)&loginData, sizeof(PacketTypeLoginT)); // Must encode each packet - no reusing encoded data.
packetSend(__packetThreadData, &encoded);
// Send CLIENT_SHUTDOWN.
logWrite("Sending CLIENT_SHUTDOWN\n");

675
gpl-3.0.md Normal file
View file

@ -0,0 +1,675 @@
### 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>.

View file

@ -36,7 +36,6 @@ HEADERS = \
$$SHARED/stddclmr.h \
$$SHARED/thirdparty/stb_ds.h \
$$SHARED/thirdparty/memwatch/memwatch.h \
$$SHARED/thirdparty/blowfish-api/blowfish.h \
$$SHARED/thirdparty/ini/src/ini.h \
$$SHARED/thirdparty/enet/include/enet.h \
$$SHARED/array.h \
@ -45,6 +44,9 @@ HEADERS = \
$$SHARED/util.h \
$$SHARED/primes.h \
$$SHARED/packet.h \
$$SHARED/packets.h \
$$SHARED/thirdparty/tiny-AES-c/aes.h \
$$SHARED/thirdparty/tiny-AES128-C/pkcs7_padding.h \
src/client.h \
src/console.h \
src/database.h \
@ -54,13 +56,14 @@ HEADERS = \
SOURCES = \
$$SHARED/thirdparty/memwatch/memwatch.c \
$$SHARED/thirdparty/blowfish-api/blowfish.c \
$$SHARED/thirdparty/ini/src/ini.c \
$$SHARED/array.c \
$$SHARED/log.c \
$$SHARED/memory.c \
$$SHARED/util.c \
$$SHARED/packet.c \
$$SHARED/thirdparty/tiny-AES-c/aes.c \
$$SHARED/thirdparty/tiny-AES128-C/pkcs7_padding.c \
src/client.c \
src/console.c \
src/database.c \

View file

@ -66,6 +66,14 @@ static void clientProcessPacket(ClientThreadT *client, PacketDecodeDataT *data)
PacketEncodeDataT encoded = { 0 };
switch (data->packetType) {
case PACKET_TYPE_CLIENT_SHUTDOWN:
serverDisconnectClient(client);
break;
case PACKET_TYPE_LOGIN:
consoleMessageQueue("%ld: Channel %d %s %s\n", client->threadIndex, data->channel, ((PacketTypeLoginT *)data->data)->user, ((PacketTypeLoginT *)data->data)->pass);
break;
case PACKET_TYPE_PING:
// Build PONG packet.
encoded.control = PACKET_CONTROL_DAT;
@ -78,10 +86,6 @@ static void clientProcessPacket(ClientThreadT *client, PacketDecodeDataT *data)
logWrite("Got PING, sent PONG\n\r");
break;
case PACKET_TYPE_CLIENT_SHUTDOWN:
serverDisconnectClient(client);
break;
default:
consoleMessageQueue("%ld: Channel %d Unknown Packet %d\n", client->threadIndex, data->channel, data->packetType);
break;

View file

@ -18,22 +18,45 @@
*/
// Reliability: https://github.com/BaroboRobotics/libsfp/wiki/Serial-Framing-Protocol
// Key Exchange: https://www.techiedelight.com/c-program-demonstrate-diffie-hellman-algorithm
// Encryption: https://erev0s.com/blog/tiny-aes-cbc-mode-pkcs7-padding-written-c
#include "packet.h"
#include "primes.h"
#define CBC 1
#include "thirdparty/tiny-AES-c/aes.h"
#include "thirdparty/tiny-AES128-C/pkcs7_padding.h"
static packetSender _packetSender = NULL;
static uint8_t packetCRC(char *data, uint16_t length, uint8_t startAt);
static uint16_t packetDHCompute(uint16_t a, uint16_t m, uint16_t n);
static void *packetAesContextCreate(uint8_t *key, uint8_t *iv);
static uint8_t packetCRC(char *data, uint16_t length, uint8_t startAt);
static uint16_t packetDHCompute(uint32_t a, uint32_t m, uint32_t n);
static void *packetAesContextCreate(uint8_t *key, uint8_t *iv) {
struct AES_ctx *ctx = NULL;
NEW(struct AES_ctx, ctx);
if (ctx) {
// Both bits parameters are 128 bits in length (16 bytes).
AES_init_ctx_iv(ctx, key, iv);
}
return ctx;
}
static uint8_t packetCRC(char *data, uint16_t length, uint8_t startAt) {
uint16_t x = 0;
for (x=0; x<length; x++) {
startAt ^= data[x]; // Good ole' XOR.
startAt ^= data[x] + data[x]; // Just XOR and increment.
}
return startAt;
@ -42,6 +65,7 @@ static uint8_t packetCRC(char *data, uint16_t length, uint8_t startAt) {
uint8_t packetDecode(PacketThreadDataT *threadData, PacketDecodeDataT *data, char *input, uint16_t length) {
uint8_t sequence = 0;
uint16_t unpadded = 0;
int32_t x = 0;
char c = 0;
PacketEncodeDataT encoded = { 0 };
@ -135,9 +159,13 @@ uint8_t packetDecode(PacketThreadDataT *threadData, PacketDecodeDataT *data, cha
data->packetType = threadData->decodeBuffer[1];
data->channel = threadData->decodeBuffer[2];
// ***TODO*** Blowfish Decryption.
// AES Decryption.
if (threadData->decodeBuffer[0] & 32) {
AES_ctx_set_iv(threadData->aesContext, (uint8_t *)threadData->dhModulus);
AES_CBC_decrypt_buffer(threadData->aesContext, (uint8_t *)&threadData->decodeBuffer[3], data->length - 4);
unpadded = pkcs7_padding_data_length((uint8_t *)&threadData->decodeBuffer[3], data->length - 4, 16);
// Fix length.
data->length = unpadded + 4;
}
// Copy packet data to new buffer, if any.
@ -158,14 +186,12 @@ uint8_t packetDecode(PacketThreadDataT *threadData, PacketDecodeDataT *data, cha
memcpy(threadData->dhBase, &data->data[PACKET_ENCRYPT_KEY_SIZE * 2], PACKET_ENCRYPT_KEY_SIZE * sizeof(uint16_t));
memcpy(threadData->dhTheirPublic, &data->data[PACKET_ENCRYPT_KEY_SIZE * 4], PACKET_ENCRYPT_KEY_SIZE * sizeof(uint16_t));
DEL(data->data);
logWrite("Server Key: ");
for (x=0; x<PACKET_ENCRYPT_KEY_SIZE; x++) {
threadData->dhMySecret[x] = rand();
threadData->dhMyPublic[x] = packetDHCompute(threadData->dhBase[x], threadData->dhMySecret[x], threadData->dhModulus[x]);
threadData->dhSharedKey[x] = packetDHCompute(threadData->dhTheirPublic[x], threadData->dhMySecret[x], threadData->dhModulus[x]);
logWrite("%d ", threadData->dhSharedKey[x]);
}
logWrite("\n\r");
threadData->aesContext = packetAesContextCreate((uint8_t *)threadData->dhSharedKey, (uint8_t *)threadData->dhModulus);
encoded.control = PACKET_CONTROL_DAT;
encoded.packetType = PACKET_TYPE_DH_RESPONSE;
encoded.channel = 0; // Doesn't matter for DH_RESPONSE.
@ -179,12 +205,10 @@ uint8_t packetDecode(PacketThreadDataT *threadData, PacketDecodeDataT *data, cha
if (data->packetType == PACKET_TYPE_DH_RESPONSE) {
memcpy(threadData->dhTheirPublic, data->data, PACKET_ENCRYPT_KEY_SIZE * sizeof(uint16_t));
DEL(data->data);
logWrite("Client Key: ");
for (x=0; x<PACKET_ENCRYPT_KEY_SIZE; x++) {
threadData->dhSharedKey[x] = packetDHCompute(threadData->dhTheirPublic[x], threadData->dhMySecret[x], threadData->dhModulus[x]);
logWrite("%d ", threadData->dhSharedKey[x]);
}
logWrite("\n\r");
threadData->aesContext = packetAesContextCreate((uint8_t *)threadData->dhSharedKey, (uint8_t *)threadData->dhModulus);
continue;
}
@ -223,12 +247,9 @@ void packetDecodeDataDestroy(PacketDecodeDataT **packet) {
}
static uint16_t packetDHCompute(uint16_t a, uint16_t m, uint16_t n) {
// See: https://www.techiedelight.com/c-program-demonstrate-diffie-hellman-algorithm/
uint16_t r = 0;
uint16_t y = 1;
static uint16_t packetDHCompute(uint32_t a, uint32_t m, uint32_t n) {
uint32_t r = 0;
uint32_t y = 1;
while (m > 0) {
r = m % 2;
@ -245,8 +266,12 @@ static uint16_t packetDHCompute(uint16_t a, uint16_t m, uint16_t n) {
uint8_t packetEncode(PacketThreadDataT *threadData, PacketEncodeDataT *data, char *input, uint16_t length) {
uint8_t crc = 0;
uint8_t control = 0;
uint16_t x = 0;
uint8_t crc = 0;
uint8_t control = 0;
uint16_t paddedSize = 0;
uint16_t inputLength = 0;
char *inputBuffer = NULL;
// Returns 1 on success, 0 on failure.
@ -263,11 +288,10 @@ uint8_t packetEncode(PacketThreadDataT *threadData, PacketEncodeDataT *data, cha
// Make needed header bytes.
control = (((uint8_t)data->control) << 6) + (data->encrypt << 5) + (data->sequence & 0x1f);
// Calculate CRC over header bytes and payload.
// Calculate CRC over header bytes.
crc = packetCRC((char *)&control, 1, crc);
crc = packetCRC((char *)&data->packetType, 1, crc);
crc = packetCRC((char *)&data->channel, 1, crc);
crc = packetCRC(input, length, crc);
// Add header bytes.
threadData->encodeBuffer[data->length++] = control;
@ -277,17 +301,35 @@ uint8_t packetEncode(PacketThreadDataT *threadData, PacketEncodeDataT *data, cha
threadData->encodeBuffer[data->length++] = data->channel;
if (data->channel == PACKET_FRAME) threadData->encodeBuffer[data->length++] = PACKET_FRAME;
// ***TODO*** Blowfish Encryption.
// AES Encryption.
if (data->encrypt) {
AES_ctx_set_iv(threadData->aesContext, (uint8_t *)threadData->dhModulus);
if (length % 16) {
paddedSize = length + 16 - (length % 16);
} else {
paddedSize = length;
}
memset(threadData->encryptionBuffer, 0, PACKET_MAX);
for (x=0; x<length; x++) threadData->encryptionBuffer[x] = input[x];
pkcs7_padding_pad_buffer(threadData->encryptionBuffer, length, paddedSize, 16);
AES_CBC_encrypt_buffer(threadData->aesContext, threadData->encryptionBuffer, paddedSize);
// Encrypted, select proper buffer.
inputBuffer = (char *)threadData->encryptionBuffer;
inputLength = paddedSize;
} else {
// Not encrypted, select proper buffer.
inputBuffer = input;
inputLength = length;
}
// Add payload.
while (length--) {
while (inputLength--) {
// Is this a frame character? If so, escape it.
if (*input == PACKET_FRAME) threadData->encodeBuffer[data->length++] = PACKET_FRAME;
if (*inputBuffer == PACKET_FRAME) threadData->encodeBuffer[data->length++] = PACKET_FRAME;
// CRC data.
crc = packetCRC(inputBuffer, 1, crc);
// Add data.
threadData->encodeBuffer[data->length++] = *input++;
threadData->encodeBuffer[data->length++] = *inputBuffer++;
}
// Add CRC.
@ -307,6 +349,16 @@ uint8_t packetEncode(PacketThreadDataT *threadData, PacketEncodeDataT *data, cha
void packetEncryptionSetup(PacketThreadDataT *threadData) {
PacketEncodeDataT encoded = { 0 };
uint16_t dhData[PACKET_ENCRYPT_KEY_SIZE * 3] = { 0 };
uint8_t x = 0;
// Only call this from ONE SIDE of the connection. It sets up both sides.
for (x=0; x<PACKET_ENCRYPT_KEY_SIZE; x++) {
threadData->dhModulus[x] = PRIMES[rand() % PRIME_COUNT];
threadData->dhBase[x] = (rand() < (RAND_MAX / 2) ? 2 : 5);
threadData->dhMySecret[x] = rand();
threadData->dhMyPublic[x] = packetDHCompute(threadData->dhBase[x], threadData->dhMySecret[x], threadData->dhModulus[x]);
}
memcpy(&dhData[0], threadData->dhModulus, PACKET_ENCRYPT_KEY_SIZE * sizeof(uint16_t));
memcpy(&dhData[PACKET_ENCRYPT_KEY_SIZE], threadData->dhBase, PACKET_ENCRYPT_KEY_SIZE * sizeof(uint16_t));
@ -331,6 +383,7 @@ void packetSend(PacketThreadDataT *threadData, PacketEncodeDataT *data) {
// Add to history?
if (data->control == PACKET_CONTROL_DAT) {
//***TODO*** Must change control to use CONTROL_RTX & fix framing changes
threadData->history[threadData->historyPosition].sequence = data->sequence;
threadData->history[threadData->historyPosition].length = data->length;
memcpy(threadData->history[threadData->historyPosition].data, data->dataPointer, data->length);
@ -352,7 +405,6 @@ void packetSenderRegister(packetSender sender) {
PacketThreadDataT *packetThreadDataCreate(void *senderData) {
PacketThreadDataT *data = NULL;
uint8_t x = 0;
data = (PacketThreadDataT *)malloc(sizeof(PacketThreadDataT));
if (data) {
@ -363,12 +415,7 @@ PacketThreadDataT *packetThreadDataCreate(void *senderData) {
data->decodeQueueTail = 0;
data->newPacket = 1;
data->senderData = senderData;
for (x=0; x<PACKET_ENCRYPT_KEY_SIZE; x++) {
data->dhModulus[x] = PRIMES[rand() % PRIME_COUNT];
data->dhBase[x] = (rand() < (RAND_MAX / 2) ? 2 : 5);
data->dhMySecret[x] = rand();
data->dhMyPublic[x] = packetDHCompute(data->dhBase[x], data->dhMySecret[x], data->dhModulus[x]);
}
data->aesContext = NULL;
}
return data;
@ -378,6 +425,7 @@ PacketThreadDataT *packetThreadDataCreate(void *senderData) {
void packetThreadDataDestroy(PacketThreadDataT **data) {
PacketThreadDataT *d = *data;
if (d->aesContext) free(d->aesContext);
free(d);
d = NULL;
*data = d;

View file

@ -23,6 +23,7 @@
#include "os.h"
#include "packets.h"
/*
@ -36,8 +37,6 @@
* Byte X0: dddd dddd /
* Byte X1: cccc cccc - Checksum
*
* Inspired by https://github.com/BaroboRobotics/libsfp/wiki/Serial-Framing-Protocol
*
*/
@ -45,11 +44,11 @@
#define PACKET_SEQUENCE_MAX 16 // Five bits of data, 32 max.
#define PACKET_INPUT_QUEUE_SIZE 4096
#define PACKET_BUFFER_SIZE (PACKET_MAX * 2 + 2 + 8) // Worst case, every byte is a PACKET_FRAME. Add two for ending frame. Add 8 for worst case header and CRC.
#define PACKET_BUFFER_SIZE (PACKET_MAX * 2 + 2 + 8) // Worst case, every byte is a PACKET_FRAME. Add two for ending frame. Add 8 for worst case header and CRC.
#define PACKET_FRAME 0x7e
#define PACKET_ENCRYPT_KEY_SIZE 32
#define PACKET_ENCRYPT_KEY_SIZE 8 // 16 bits each. Provides 16 bytes (128 bits) of keydata.
// This enum must be 4 entries or less.
@ -61,18 +60,6 @@ typedef enum PacketControlE {
PACKET_CONTROL_COUNT
} PacketControlT;
// This enum is treated as BYTES in the code. Do not go over 255 entries.
typedef enum PacketTypeE {
PACKET_TYPE_NONE = 0, // No packet.
PACKET_TYPE_PING,
PACKET_TYPE_PONG,
PACKET_TYPE_SERVER_SHUTDOWN,
PACKET_TYPE_CLIENT_SHUTDOWN,
PACKET_TYPE_DH_REQUEST,
PACKET_TYPE_DH_RESPONSE,
PACKET_TYPE_COUNT
} PacketTypeT;
typedef struct PacketDecodeDataS {
// Output
@ -121,6 +108,8 @@ typedef struct PacketThreadDataS {
uint16_t dhMyPublic[PACKET_ENCRYPT_KEY_SIZE];
uint16_t dhTheirPublic[PACKET_ENCRYPT_KEY_SIZE];
uint16_t dhSharedKey[PACKET_ENCRYPT_KEY_SIZE];
uint8_t encryptionBuffer[PACKET_MAX];
void *aesContext;
} PacketThreadDataT;

53
shared/packets.h Normal file
View file

@ -0,0 +1,53 @@
/*
* Kangaroo Punch MultiPlayer Game Server Mark II
* Copyright (C) 2020-2021 Scott Duensing
*
* 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/>.
*
*/
#ifndef PACKETS_H
#define PACKETS_H
#define PACKET_MAX_USER 16
#define PACKET_MAX_PASS 16
// This enum is treated as BYTES in the code. Do not go over 255 entries.
typedef enum PacketTypeE {
PACKET_TYPE_NONE = 0, // No packet.
PACKET_TYPE_PING,
PACKET_TYPE_PONG,
PACKET_TYPE_SERVER_SHUTDOWN,
PACKET_TYPE_CLIENT_SHUTDOWN,
PACKET_TYPE_DH_REQUEST,
PACKET_TYPE_DH_RESPONSE,
PACKET_TYPE_LOGIN,
PACKET_TYPE_COUNT
} PacketTypeT;
#pragma pack(push, 1)
typedef struct PacketTypeLoginS {
char user[PACKET_MAX_USER];
char pass[PACKET_MAX_PASS];
} PacketTypeLoginT;
#pragma pack(pop)
#endif // PACKETS_H

View file

@ -1,25 +0,0 @@
TARGET = blowfish_test
LIBS = -lgomp
CC = gcc
CFLAGS = -std=c99 -Wall -Wextra -Werror -pedantic -O3 -I ./ -fopenmp
LDFLAGS =
.PHONY: default all clean
default: $(TARGET)
all: default
OBJECTS = $(patsubst %.c, %.o, $(wildcard *.c))
HEADERS = $(wildcard *.h)
%.o: %.c $(HEADERS)
$(CC) $(CFLAGS) -c $< -o $@
.PRECIOUS: $(TARGET) $(OBJECTS)
$(TARGET): $(OBJECTS)
$(CC) $(OBJECTS) $(LIBS) -o $@
clean:
-rm -f *.o
-rm -f $(TARGET)

View file

@ -1,4 +0,0 @@
blowfish-api
============
Portable, optimised implementation of Bruce Schneier's 64-bit symmetric block cipher, Blowfish. Includes support for multiple block cipher modes, including electronic codebook (ECB), cipher block chaining (CBC), cipher feedback (CFB), output feedback (OFB) and counter (CTR), as well as support for weak key detection and parallelisation using OpenMP.

File diff suppressed because it is too large Load diff

View file

@ -1,408 +0,0 @@
/**
@file blowfish.h
@brief Public interface for Bruce Schneier's 64-bit symmetric block
cipher, Blowfish.
@author Tom Bonner (tom.bonner@gmail.com)
@date 15-June-2008
Copyright (c) 2008, Tom Bonner.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
Except as contained in this notice, the name(s) of the above copyright
holders shall not be used in advertising or otherwise to promote the sale,
use or other dealings in this Software without prior written authorisation.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#ifndef __BLOWFISH_H__
#define __BLOWFISH_H__
/**
@ingroup blowfish
@defgroup blowfish_api Blowfish API
@{
*/
#ifdef __cplusplus
extern "C"
{
#endif
/* Definitions for fixed sized types required by Blowfish, to be redefined where necessary. */
typedef unsigned char BLOWFISH_UCHAR; /*!< Must be an 8-bit unsigned type. */
typedef BLOWFISH_UCHAR * BLOWFISH_PUCHAR; /*!< Must be a pointer to an 8-bit unsigned type. */
typedef const BLOWFISH_UCHAR * BLOWFISH_PCUCHAR; /*!< Must be a pointer to a constant 8-bit unsigned type */
typedef unsigned int BLOWFISH_ULONG; /*!< Must be a 32-bit unsigned type. */
typedef BLOWFISH_ULONG * BLOWFISH_PULONG; /*!< Must be a pointer to a 32-bit unsigned type. */
typedef const BLOWFISH_ULONG * BLOWFISH_PCULONG; /*!< Must be a pointer to a constant 32-bit unsigned type. */
/* Note! Altering the size and/or signedness of BLOWFISH_SIZE_T will affect the amount of data that can be enciphed/deciphered! */
#ifdef _OPENMP
typedef signed long BLOWFISH_SIZE_T; /*!< Must be a signed 32 or 64-bit type for use with OpenMP. */
#else
typedef unsigned long BLOWFISH_SIZE_T; /*!< Must be an unsigned 32 or 64-bit type. */
#endif
/** Blowfish block cipher modes. */
typedef enum _BLOWFISH_MODE
{
BLOWFISH_MODE_CURRENT = 0, /*!< For use only with #BLOWFISH_Reset to re-use the mode that the context record was initialised with. */
BLOWFISH_MODE_ECB, /*!< Electronic codebook mode. Encipher/Decipher data in 8-byte blocks. This mode is weak at masking repeating patterns, and therefore insecure, but can be parallelised. */
BLOWFISH_MODE_CBC, /*!< Cipher block chaining mode (recommended). XOR plaintext block with previous cipher text block before encrypting. This mode cannot be parallelised for encryption. */
BLOWFISH_MODE_CFB, /*!< Cipher feedback mode. Plaintext is XOR encrypted with previous block of ciphertext. This mode cannot be parallelised for encryption. */
BLOWFISH_MODE_OFB, /*!< Ouput feedback mode. Plaintext is XOR encrypted with enciphered initialisation vector. This mode cannot be parallelised. */
BLOWFISH_MODE_CTR /*!< Counter mode. Plaintext is XOR encrypted with enciphered initialisation vector added with a counter. This mode can be parallelised for encryption/decryption. */
} BLOWFISH_MODE;
/** Blowfish return codes. */
typedef enum _BLOWFISH_RC
{
BLOWFISH_RC_SUCCESS = 0, /*!< Function completed successfully. */
BLOWFISH_RC_INVALID_PARAMETER, /*!< One of the parameters suppied to the function is invalid (null pointer). */
BLOWFISH_RC_INVALID_KEY, /*!< The length of the key supplied to the #BLOWFISH_Init/#BLOWFISH_Reset function is either greater than #BLOWFISH_MAX_KEY_LENGTH or less than #BLOWFISH_MIN_KEY_LENGTH. */
BLOWFISH_RC_WEAK_KEY, /*!< The key supplied to the #BLOWFISH_Init/#BLOWFISH_Reset function has been deemed to be weak, and should not be used. */
BLOWFISH_RC_BAD_BUFFER_LENGTH, /*!< The size of the buffer supplied to one of the encipher/decipher buffer/stream functions is not a multiple of 8. */
BLOWFISH_RC_INVALID_MODE, /*!< The mode specified to the #BLOWFISH_Init/#BLOWFISH_Reset function is not supported. */
BLOWFISH_RC_TEST_FAILED, /*!< Self test failed. For more information see stdout (only used by test applications). */
BLOWFISH_RC_ERROR, /*!< Generic error (only used by test applications). */
} BLOWFISH_RC;
/* Various static array/buffer lengths (do not modify!). */
#define BLOWFISH_SUBKEYS 18 /*!< Number of subkeys in the P-Array. */
#define BLOWFISH_SBOXES 4 /*!< Number of S-Boxes. */
#define BLOWFISH_SBOX_ENTRIES 256 /*!< Number of entries in each S-Box. */
#define BLOWFISH_MIN_KEY_LENGTH 4 /*!< Maximum length of a key (4-bytes, or 32-bits). */
#define BLOWFISH_MAX_KEY_LENGTH 56 /*!< Maximum length of a key (56-bytes, or 448-bits). */
/** Blowfish context record. */
typedef struct _BLOWFISH_CONTEXT
{
BLOWFISH_ULONG PArray [ BLOWFISH_SUBKEYS ]; /*!< Original P-Array which has been XOR'd with the key, and overwritten with output from #BLOWFISH_Encipher. */
BLOWFISH_ULONG SBox [ BLOWFISH_SBOXES ] [ BLOWFISH_SBOX_ENTRIES ]; /*!< Original S-Boxes which have been overwritten with output from #BLOWFISH_Encipher. */
BLOWFISH_ULONG OriginalIvHigh32; /*!< Original high 32-bytes of the initialisation vector. */
BLOWFISH_ULONG OriginalIvLow32; /*!< Original low 32-bytes of the initialisation vector. */
BLOWFISH_ULONG IvHigh32; /*!< Current high 32-bytes of the initialisation vector (used for stream operations). */
BLOWFISH_ULONG IvLow32; /*!< Current low 32-bytes of the initialisation vector (used for stream operations). */
void ( *EncipherStream ) ( ); /*!< Pointer to a callback function to perform the encipher based on the block cipher mode */
void ( *DecipherStream ) ( ); /*!< Pointer to a callback function to perform the decipher based on the block cipher mode */
} BLOWFISH_CONTEXT, *BLOWFISH_PCONTEXT;
/* Function prototypes. */
/**
Initialise a Blowfish context record.
@param Context Pointer to a Blowfish context record to initialise.
@param Key Pointer to a key to use for enciphering/deciphering data.
@param KeyLength Length of the key, which cannot exceed #BLOWFISH_MAX_KEY_LENGTH bytes (sizeof(#BLOWFISH_CONTEXT::PArray)), or be less than #BLOWFISH_MIN_KEY_LENGTH bytes.
@param Mode Mode to use when enciphering/decipering blocks. For supported modes see #BLOWFISH_MODE
@param IvHigh32 High 32-bits of the initialisation vector. Required if the Mode parameter is not #BLOWFISH_MODE_ECB.
@param IvLow32 Low 32-bits of the initialisation vector. Required if the Mode parameter is not #BLOWFISH_MODE_ECB.
@remarks For stream based enciphering/deciphering, call #BLOWFISH_BeginStream/#BLOWFISH_EndStream before/afer processing the stream.
@remarks Operations performed on a blowfish context record are not thread safe. Use #BLOWFISH_CloneContext to create a copy of a context record that can be safely used by another thread.
@return #BLOWFISH_RC_SUCCESS Initialised context record successfully.
@return #BLOWFISH_RC_INVALID_PARAMETER Either the context record or key pointer is null.
@return #BLOWFISH_RC_INVALID_KEY The key is either too short or too long.
@return #BLOWFISH_RC_WEAK_KEY The key has been deemed to be weak.
@return #BLOWFISH_RC_INVALID_MODE The specified mode is not supported.
*/
BLOWFISH_RC BLOWFISH_Init ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCUCHAR Key, BLOWFISH_SIZE_T KeyLength, BLOWFISH_MODE Mode, BLOWFISH_ULONG IvHigh32, BLOWFISH_ULONG IvLow32 );
/**
Reinitialise either the key and/or mode and initialisation vector in a Blowfish context record.
@param Context Pointer to an initialised Blowfish context record to reinitialise.
@param Key Pointer to a new key to use for enciphering/deciphering data. (May be null to re-use the current key).
@param KeyLength Length of the new key, which cannot exceed #BLOWFISH_MAX_KEY_LENGTH bytes (sizeof(#BLOWFISH_CONTEXT::PArray)), or be less than #BLOWFISH_MIN_KEY_LENGTH bytes. (May be 0 if Key is null).
@param Mode New mode to use when enciphering/decipering blocks. Use #BLOWFISH_MODE_CURRENT to re-use the current mode and initialisation vector. For supported modes see #BLOWFISH_MODE.
@param IvHigh32 High 32-bits of the new initialisation vector. Required if the Mode parameter is not #BLOWFISH_MODE_ECB or #BLOWFISH_MODE_CURRENT.
@param IvLow32 Low 32-bits of the new initialisation vector. Required if the Mode parameter is not #BLOWFISH_MODE_ECB or #BLOWFISH_MODE_CURRENT.
@remarks See #BLOWFISH_Init remarks.
@return #BLOWFISH_RC_SUCCESS Reinitialised the context record successfully.
@return #BLOWFISH_RC_INVALID_PARAMETER The context record pointer is null.
@return #BLOWFISH_RC_INVALID_KEY The key is either too short or too long.
@return #BLOWFISH_RC_WEAK_KEY The key has been deemed to be weak.
@return #BLOWFISH_RC_INVALID_MODE The specified mode is not supported.
*/
BLOWFISH_RC BLOWFISH_Reset ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCUCHAR Key, BLOWFISH_SIZE_T KeyLength, BLOWFISH_MODE Mode, BLOWFISH_ULONG IvHigh32, BLOWFISH_ULONG IvLow32 );
/**
Copy an initialised context record into an uninitialised context record for use in another thread.
@param InContext Pointer to an initialised context record.
@param OutContext Pointer to an uninitialised context record.
@remarks Destroy the cloned context record using #BLOWFISH_Exit.
@return BLOWFISH_RC_SUCCESS The context record was cloned successfully.
@return BLOWFISH_RC_INVALID_PARAMETER One of the context record pointers is null.
*/
BLOWFISH_RC BLOWFISH_CloneContext ( BLOWFISH_PCONTEXT InContext, BLOWFISH_PCONTEXT OutContext );
/**
Clear a blowfish context record.
@param Context Pointer to an initialised context record to overwrite.
@remarks Call this function regardless of whether #BLOWFISH_Init succeeds.
@remarks It is a security risk to not call this function once you have finished enciphering/deciphering data!
@remarks The context record may not be used again after this call without first calling #BLOWFISH_Init.
@return #BLOWFISH_RC_SUCCESS The context record was overwritten successfully.
@return #BLOWFISH_RC_INVALID_PARAMETER The supplied context record pointer is null.
*/
BLOWFISH_RC BLOWFISH_Exit ( BLOWFISH_PCONTEXT Context );
/**
Initialise a context record for stream based enciphering/deciphering.
@param Context Pointer to an initialised context record.
@remarks Before re-using the context record to process another stream, be sure to end and begin a new stream using #BLOWFISH_EndStream and BLOWFISH_BeginStream.
@remarks After calling BLOWFISH_BeginStream, the context will become corrupt if it is passed to any function other than #BLOWFISH_EncipherStream/#BLOWFISH_DecipherStream before calling #BLOWFISH_EndStream.
@return #BLOWFISH_RC_SUCCESS The context record was initialised for stream ciphering successfully.
@return #BLOWFISH_RC_INVALID_PARAMETER The supplied context record pointer is null.
*/
BLOWFISH_RC BLOWFISH_BeginStream ( BLOWFISH_PCONTEXT Context );
/**
Clear sensitive data from a context record after performing stream based enciphering/deciphering.
@param Context Pointer to an initialised context record.
@remarks The context record may be re-used after this call without needing to call #BLOWFISH_Init again.
@remarks After calling BLOWFISH_EndStream, the context record may be used in non-stream based functions without risking corruption. (See #BLOWFISH_BeginStream remarks)
@return #BLOWFISH_RC_SUCCESS Sensitive data was cleared from the context record successfully.
@return #BLOWFISH_RC_INVALID_PARAMETER The supplied context record pointer is null.
*/
BLOWFISH_RC BLOWFISH_EndStream ( BLOWFISH_PCONTEXT Context );
/**
Encipher an 8-byte block of data.
@param Context Pointer to an initialised context record.
@param High32 Pointer to the high 32 bits of data to encipher.
@param Low32 Pointer to the low 32 bits of data to encipher.
@remarks It is an unchecked runtime error to supply a null parameter to this function.
*/
void BLOWFISH_Encipher ( BLOWFISH_PCONTEXT Context, BLOWFISH_PULONG High32, BLOWFISH_PULONG Low32 );
/**
Encipher a buffer of data as part of a stream.
@param Context Pointer to an initialised context record.
@param PlainTextStream Pointer to a buffer of data to encipher within the stream.
@param CipherTextStream Pointer to a buffer within the stream to receive the enciphered data.
@param StreamLength Length of the plaintext and ciphertext stream buffers. Must be a multiple of 8.
@remarks The PlainTextStream and CipherTextStream pointers may overlap if the mode used to initialise the context was either #BLOWFISH_MODE_ECB or #BLOWFISH_MODE_CTR.
@remarks The PlainTextStream and CipherTextStream pointers must point to an offset within the stream that is a multiple of 8.
@return #BLOWFISH_RC_SUCCESS Successfully enciphered data.
@return #BLOWFISH_RC_INVALID_PARAMETER Either the context record or one of the stream buffer pointer is null.
@return #BLOWFISH_RC_BAD_BUFFER_LENGTH The size of the stream buffer is not a multiple of 8.
*/
BLOWFISH_RC BLOWFISH_EncipherStream ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCUCHAR PlainTextStream, BLOWFISH_PUCHAR CipherTextStream, BLOWFISH_SIZE_T StreamLength );
/**
Encipher a buffer of data.
@param Context Pointer to an initialised context record.
@param PlainTextBuffer Pointer to a buffer of data to encipher.
@param CipherTextBuffer Pointer to a buffer to receive the enciphered data.
@param BufferLength Length of the plaintext and ciphertext buffers. Must be a multiple of 8.
@remarks The PlainTextBuffer and CipherTextBuffer pointers may overlap if the mode used to initialise the context was either #BLOWFISH_MODE_ECB or #BLOWFISH_MODE_CTR.
@return #BLOWFISH_RC_SUCCESS Successfully enciphered data.
@return #BLOWFISH_RC_INVALID_PARAMETER Either the context record or one of the buffer pointer is null.
@return #BLOWFISH_RC_BAD_BUFFER_LENGTH The size of the buffer is not a multiple of 8.
*/
BLOWFISH_RC BLOWFISH_EncipherBuffer ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCUCHAR PlainTextBuffer, BLOWFISH_PUCHAR CipherTextBuffer, BLOWFISH_SIZE_T BufferLength );
/**
Decipher an 8-byte block of data.
@param Context Pointer to an initialised context record.
@param High32 Pointer to the high 32 bits of data to decipher.
@param Low32 Pointer to the low 32 bits of data to decipher.
@remarks It is an unchecked runtime error to supply a null parameter to this function.
*/
void BLOWFISH_Decipher ( BLOWFISH_PCONTEXT Context, BLOWFISH_PULONG High32, BLOWFISH_PULONG Low32 );
/**
Decipher a buffer of data as part of a stream.
@param Context Pointer to an initialised context record.
@param CipherTextStream Pointer to a buffer of data to decipher within the stream.
@param PlainTextStream Pointer to a buffer within the stream to receive the deciphered data.
@param StreamLength Length of the plaintext and ciphertext stream buffers. Must be a multiple of 8.
@remarks The PlainTextStream and CipherTextStream pointers may overlap if the mode used to initialise the context was either #BLOWFISH_MODE_ECB or #BLOWFISH_MODE_CTR.
@remarks The PlainTextStream and CipherTextStream pointers must point to an offset within the stream that is a multiple of 8.
@return #BLOWFISH_RC_SUCCESS Successfully enciphered data.
@return #BLOWFISH_RC_INVALID_PARAMETER Either the context record or one of the stream buffer pointer is null.
@return #BLOWFISH_RC_BAD_BUFFER_LENGTH The size of the stream buffer is not a multiple of 8.
*/
BLOWFISH_RC BLOWFISH_DecipherStream ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCUCHAR CipherTextStream, BLOWFISH_PUCHAR PlainTextStream, BLOWFISH_SIZE_T StreamLength );
/**
Decipher a buffer of data.
@param Context Pointer to an initialised context record.
@param CipherTextBuffer Pointer to a buffer of data to decipher.
@param PlainTextBuffer Pointer to a buffer to receive the deciphered data.
@param BufferLength Length of the ciphertext and plaintext buffers. Must be a multiple of 8.
@remarks The PlainTextBuffer and CipherTextBuffer pointers may overlap if the mode used to initialise the context was either #BLOWFISH_MODE_ECB or #BLOWFISH_MODE_CTR.
@return #BLOWFISH_RC_SUCCESS Successfully enciphered data.
@return #BLOWFISH_RC_INVALID_PARAMETER Either the context record or one of the buffer pointer is null.
@return #BLOWFISH_RC_BAD_BUFFER_LENGTH The size of the buffer is not a multiple of 8.
*/
BLOWFISH_RC BLOWFISH_DecipherBuffer ( BLOWFISH_PCONTEXT Context, BLOWFISH_PCUCHAR CipherTextBuffer, BLOWFISH_PUCHAR PlainTextBuffer, BLOWFISH_SIZE_T BufferLength );
#ifdef __cplusplus
}
#endif
/** @} */
#endif /* __BLOWFISH_H__ */

View file

@ -1,891 +0,0 @@
/**
@file blowfish_test.c
@brief Blowfish self-test application. Includes standard ECB mode
tests and throughput tests (parallel and serial) for all
supported modes (ECB, CBC, CFB, OFB and CTR).
@author Tom Bonner (tom.bonner@gmail.com)
@date 22-June-2008
Copyright (c) 2008, Tom Bonner.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
Except as contained in this notice, the name(s) of the above copyright
holders shall not be used in advertising or otherwise to promote the sale,
use or other dealings in this Software without prior written authorisation.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <stdio.h>
#include <time.h>
#include <malloc.h>
#include <memory.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#include <blowfish.h>
/**
@ingroup blowfish
@defgroup blowfish_selftest Blowfish Self-Test
@{
*/
/** @internal Test vector. */
typedef struct __BLOWFISH_TEST_VECTOR
{
BLOWFISH_UCHAR Key [ 8 ]; /*!< 8-Byte key to use in the test. */
BLOWFISH_ULONG PlainText [ 2 ]; /*!< 8-Byte block of plaintext to encipher. */
BLOWFISH_ULONG CipherText [ 2 ]; /*!< 8-Byte block of expected ciphertext. */
} _BLOWFISH_TEST_VECTOR;
/** @internal ECB Test vector data from http://www.mirrors.wiretapped.net/security/cryptography/algorithms/blowfish/blowfish-TESTVECTORS.txt */
static const _BLOWFISH_TEST_VECTOR _BLOWFISH_EcbTv1 [ ] =
{
{ { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x00000000, 0x00000000 }, { 0x4ef99745, 0x6198dd78 } },
{ { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, { 0xffffffff, 0xffffffff }, { 0x51866fd5, 0xb85ecb8a } },
{ { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, { 0x00000000, 0x00000000 }, { 0xf21e9a77, 0xb71c49bc } },
{ { 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11 }, { 0x01234567, 0x89abcdef }, { 0x7d0cc630, 0xafda1ec7 } },
{ { 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11 }, { 0x11111111, 0x11111111 }, { 0x2466dd87, 0x8b963c9d } },
{ { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0xffffffff, 0xffffffff }, { 0x014933e0, 0xcdaff6e4 } },
{ { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 }, { 0x01234567, 0x89abcdef }, { 0xfa34ec48, 0x47b268b2 } },
{ { 0x1f, 0x1f, 0x1f, 0x1f, 0x0e, 0x0e, 0x0e, 0x0e }, { 0x01234567, 0x89abcdef }, { 0xa7907951, 0x08ea3cae } },
{ { 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x10000000, 0x00000001 }, { 0x7d856f9a, 0x613063f2 } },
{ { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef }, { 0x11111111, 0x11111111 }, { 0x61f9c380, 0x2281b096 } },
{ { 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10 }, { 0x01234567, 0x89abcdef }, { 0x0aceab0f, 0xc6a0a28d } },
{ { 0x7c, 0xa1, 0x10, 0x45, 0x4a, 0x1a, 0x6e, 0x57 }, { 0x01a1d6d0, 0x39776742 }, { 0x59c68245, 0xeb05282b } },
{ { 0x01, 0x31, 0xd9, 0x61, 0x9d, 0xc1, 0x37, 0x6e }, { 0x5cd54ca8, 0x3def57da }, { 0xb1b8cc0b, 0x250f09a0 } },
{ { 0x07, 0xa1, 0x13, 0x3e, 0x4a, 0x0b, 0x26, 0x86 }, { 0x0248d438, 0x06f67172 }, { 0x1730e577, 0x8bea1da4 } },
{ { 0x38, 0x49, 0x67, 0x4c, 0x26, 0x02, 0x31, 0x9e }, { 0x51454b58, 0x2ddf440a }, { 0xa25e7856, 0xcf2651eb } },
{ { 0x04, 0xb9, 0x15, 0xba, 0x43, 0xfe, 0xb5, 0xb6 }, { 0x42fd4430, 0x59577fa2 }, { 0x353882b1, 0x09ce8f1a } },
{ { 0x01, 0x13, 0xb9, 0x70, 0xfd, 0x34, 0xf2, 0xce }, { 0x059b5e08, 0x51cf143a }, { 0x48f4d088, 0x4c379918 } },
{ { 0x01, 0x70, 0xf1, 0x75, 0x46, 0x8f, 0xb5, 0xe6 }, { 0x0756d8e0, 0x774761d2 }, { 0x432193b7, 0x8951fc98 } },
{ { 0x43, 0x29, 0x7f, 0xad, 0x38, 0xe3, 0x73, 0xfe }, { 0x762514b8, 0x29bf486a }, { 0x13f04154, 0xd69d1ae5 } },
{ { 0x07, 0xa7, 0x13, 0x70, 0x45, 0xda, 0x2a, 0x16 }, { 0x3bdd1190, 0x49372802 }, { 0x2eedda93, 0xffd39c79 } },
{ { 0x04, 0x68, 0x91, 0x04, 0xc2, 0xfd, 0x3b, 0x2f }, { 0x26955f68, 0x35af609a }, { 0xd887e039, 0x3c2da6e3 } },
{ { 0x37, 0xd0, 0x6b, 0xb5, 0x16, 0xcb, 0x75, 0x46 }, { 0x164d5e40, 0x4f275232 }, { 0x5f99d04f, 0x5b163969 } },
{ { 0x1f, 0x08, 0x26, 0x0d, 0x1a, 0xc2, 0x46, 0x5e }, { 0x6b056e18, 0x759f5cca }, { 0x4a057a3b, 0x24d3977b } },
{ { 0x58, 0x40, 0x23, 0x64, 0x1a, 0xba, 0x61, 0x76 }, { 0x004bd6ef, 0x09176062 }, { 0x452031c1, 0xe4fada8e } },
{ { 0x02, 0x58, 0x16, 0x16, 0x46, 0x29, 0xb0, 0x07 }, { 0x480d3900, 0x6ee762f2 }, { 0x7555ae39, 0xf59b87bd } },
{ { 0x49, 0x79, 0x3e, 0xbc, 0x79, 0xb3, 0x25, 0x8f }, { 0x437540c8, 0x698f3cfa }, { 0x53c55f9c, 0xb49fc019 } },
{ { 0x4f, 0xb0, 0x5e, 0x15, 0x15, 0xab, 0x73, 0xa7 }, { 0x072d43a0, 0x77075292 }, { 0x7a8e7bfa, 0x937e89a3 } },
{ { 0x49, 0xe9, 0x5d, 0x6d, 0x4c, 0xa2, 0x29, 0xbf }, { 0x02fe5577, 0x8117f12a }, { 0xcf9c5d7a, 0x4986adb5 } },
{ { 0x01, 0x83, 0x10, 0xdc, 0x40, 0x9b, 0x26, 0xd6 }, { 0x1d9d5c50, 0x18f728c2 }, { 0xd1abb290, 0x658bc778 } },
{ { 0x1c, 0x58, 0x7f, 0x1c, 0x13, 0x92, 0x4f, 0xef }, { 0x30553228, 0x6d6f295a }, { 0x55cb3774, 0xd13ef201 } },
{ { 0xe0, 0xfe, 0xe0, 0xfe, 0xf1, 0xfe, 0xf1, 0xfe }, { 0x01234567, 0x89abcdef }, { 0xc39e072d, 0x9fac631d } },
{ { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef }, { 0x00000000, 0x00000000 }, { 0x24594688, 0x5754369a } },
{ { 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10 }, { 0xffffffff, 0xffffffff }, { 0x6b5c5a9c, 0x5d9e0a5a } }
};
/** @internal Part of ECB Test vector. See #_BLOWFISH_EcbTv1. */
static const BLOWFISH_UCHAR _BLOWFISH_EcbTv2Key [ ] = { 0xf0, 0xe1, 0xd2, 0xc3, 0xb4, 0xa5, 0x96, 0x87, 0x78, 0x69, 0x5a, 0x4b, 0x3c, 0x2d, 0x1e, 0x0f, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77 };
/** @internal Part of ECB Test vector. See #_BLOWFISH_EcbTv1. */
static const BLOWFISH_ULONG _BLOWFISH_EcbTv2PlainText [ 2 ] = { 0xfedcba98, 0x76543210 };
/** @internal Part of ECB Test vector. See #_BLOWFISH_EcbTv1. */
static const BLOWFISH_ULONG _BLOWFISH_EcbTv2CipherText [ ] [ 2 ] =
{
{ 0xbe1e6394, 0x08640f05 }, { 0xb39e4448, 0x1bdb1e6e }, { 0x9457aa83, 0xb1928c0d },
{ 0x8bb77032, 0xf960629d }, { 0xe87a244e, 0x2cc85e82 }, { 0x15750e7a, 0x4f4ec577 },
{ 0x122ba70b, 0x3ab64ae0 }, { 0x3a833c9a, 0xffc537f6 }, { 0x9409da87, 0xa90f6bf2 },
{ 0x884f8062, 0x5060b8b4 }, { 0x1f85031c, 0x19e11968 }, { 0x79d9373a, 0x714ca34f },
{ 0x93142887, 0xee3be15c }, { 0x03429e83, 0x8ce2d14b }, { 0xa4299e27, 0x469ff67b },
{ 0xafd5aed1, 0xc1bc96a8 }, { 0x10851c0e, 0x3858da9f }, { 0xe6f51ed7, 0x9b9db21f },
{ 0x64a6e14a, 0xfd36b46f }, { 0x80c7d7d4, 0x5a5479ad }, { 0x05044b62, 0xfa52d080 }
};
/** @internal Part of CBC/CFB/OFB Test vector. See #_BLOWFISH_EcbTv1. */
static const BLOWFISH_UCHAR _BLOWFISH_Tv3Key [ ] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xf0, 0xe1, 0xd2, 0xc3, 0xb4, 0xa5, 0x96, 0x87 };
/** @internal Part of CBC/CFB/OFB Test vector. See #_BLOWFISH_EcbTv1. */
static const BLOWFISH_ULONG _BLOWFISH_Tv3Iv [ 2 ] = { 0xfedcba98, 0x76543210 };
/** @internal Part of CBC/CFB/OFB Test vector. See #_BLOWFISH_EcbTv1. */
static const BLOWFISH_ULONG _BLOWFISH_Tv3PlainText [ 6 ] = { 0x37363534, 0x33323120, 0x4e6f7720, 0x69732074, 0x68652074, 0x696d6520 };
/** @internal Part of CBC/CFB/OFB Test vector. See #_BLOWFISH_EcbTv1. */
static const BLOWFISH_ULONG _BLOWFISH_Tv3CipherText [ ] [ 6 ] =
{
{ 0x6b77b4d6, 0x3006dee6, 0x05b156e2, 0x74039793, 0x58deb9e7, 0x154616d9 }, /*!< CBC mode ciphertext. */
{ 0xe73214a2, 0x822139ca, 0xf26ecf6d, 0x2eb9e76e, 0x3da3de04, 0xd1517200 }, /*!< CFB mode ciphertext. */
{ 0xe73214a2, 0x822139ca, 0x62b343cc, 0x5b655873, 0x10dd908d, 0x0c241b22 } /*!< OFB mode ciphertext. */
};
/** @internal CBC/CFB/OFB Test modes. */
static const BLOWFISH_MODE _BLOWFISH_Tv3Mode [ ] = { BLOWFISH_MODE_CBC, BLOWFISH_MODE_CFB, BLOWFISH_MODE_OFB };
/** @internal Throughput test vector */
typedef struct __BLOWFISH_THROUGHPUT_TEST
{
BLOWFISH_MODE Mode; /*!< Mode to use in the test. */
BLOWFISH_UCHAR Parallel; /*!< Specifies whether the mode can be parallelised. */
} _BLOWFISH_THROUGHPUT_TEST;
/** @internal Throughput test modes */
static const _BLOWFISH_THROUGHPUT_TEST _BLOWFISH_ThroughputTv [ ] = { { BLOWFISH_MODE_ECB, 0x01 }, { BLOWFISH_MODE_CBC, 0x01 }, { BLOWFISH_MODE_CFB, 0x01 }, { BLOWFISH_MODE_OFB, 0x00 }, { BLOWFISH_MODE_CTR, 0x01 } };
/** @internal Specifies the duration (in seconds) for how long the throughput tests should run (must be greater than 1, and preferably a multiple of 2) */
#define _BLOWFISH_THROUGHPUT_DURATION 10
#define _BLOWFISH_THROUGHPUT_STREAM_LENGTH ( 128 * 1024 )
/**
@internal
Display function name and readable return code to stdout.
@param FunctionName Name of the function called.
@param ReturnCode Return code from the function.
@return Return code from printf().
*/
static int _BLOWFISH_PrintReturnCode ( char * FunctionName, BLOWFISH_RC ReturnCode )
{
switch ( ReturnCode )
{
case BLOWFISH_RC_SUCCESS:
{
return 0;
}
case BLOWFISH_RC_INVALID_PARAMETER:
{
return printf ( "%s()=Invalid parameter!\n", FunctionName );
}
case BLOWFISH_RC_INVALID_KEY:
{
return printf ( "%s()=Invalid key!\n", FunctionName );
}
case BLOWFISH_RC_WEAK_KEY:
{
return printf ( "%s()=Weak key!\n", FunctionName );
}
case BLOWFISH_RC_BAD_BUFFER_LENGTH:
{
return printf ( "%s()=Invalid buffer length!\n", FunctionName );
}
case BLOWFISH_RC_INVALID_MODE:
{
return printf ( "%s()=Invalid mode!\n", FunctionName );
}
case BLOWFISH_RC_TEST_FAILED:
{
return printf ( "%s()=Self-test failed!\n", FunctionName );
}
default:
{
return printf ( "%s()=Unknown error!\n", FunctionName );
}
}
}
/**
@internal
Display the name of the specified mode to stdout.
@param Mode Mode to display.
@return Return code from printf().
*/
static int _BLOWFISH_PrintMode ( BLOWFISH_MODE Mode )
{
switch ( Mode )
{
case BLOWFISH_MODE_ECB:
{
return printf ( "Mode=Electronic codebook (ECB)\n" );
}
case BLOWFISH_MODE_CBC:
{
return printf ( "Mode=Cipher block chaining (CBC)\n" );
}
case BLOWFISH_MODE_CFB:
{
return printf ( "Mode=Cipher feedback (CFB)\n" );
}
case BLOWFISH_MODE_OFB:
{
return printf ( "Mode=Output feedback (OFB)\n" );
}
case BLOWFISH_MODE_CTR:
{
return printf ( "Mode=Counter (CTR)\n" );
}
default:
{
return printf ( "Mode=Invalid!\n" );
}
}
}
/**
@internal
Display a buffer as hex to stdout.
@param Name Name of the buffer.
@param Buffer Pointer to a buffer of data to display.
@param Buffer Length of the buffer.
*/
static void _BLOWFISH_PrintBuffer ( char * Name, BLOWFISH_PUCHAR Buffer, BLOWFISH_ULONG BufferLength )
{
BLOWFISH_ULONG i;
printf ( "%s=0x", Name );
for ( i = 0; i < BufferLength; i++ )
{
printf ( "%02x", Buffer [ i ] );
}
printf ( " (%d bytes)\n", (int)BufferLength );
return;
}
/**
@internal
Perform a raw ECB mode encipher/decipher on an 8-byte block of plaintext, and verify results.
@param Key Pointer to a buffer containing the key to use for cipher operations.
@param KeyLength Length of the key buffer.
@param PlainTextHigh32 High 32-bits of plaintext to encipher.
@param PlainTextLow32 Low 32-bits of plaintext to encipher.
@param CipherTextHigh32 High 32 bits of expected ciphertext.
@param CipherTextLow32 Low 32 bits of expected ciphertext.
@remarks For use with test vectors 1 and 2.
@return #BLOWFISH_RC_SUCCESS Test passed successfully.
@return Specific return code, see #BLOWFISH_RC.
*/
static BLOWFISH_RC _BLOWFISH_Test_ECB ( BLOWFISH_PUCHAR Key, BLOWFISH_ULONG KeyLength, BLOWFISH_ULONG PlainTextHigh32, BLOWFISH_ULONG PlainTextLow32, BLOWFISH_ULONG CipherTextHigh32, BLOWFISH_ULONG CipherTextLow32 )
{
BLOWFISH_RC ReturnCode = BLOWFISH_RC_SUCCESS;
BLOWFISH_CONTEXT Context;
BLOWFISH_ULONG XLeft = PlainTextHigh32;
BLOWFISH_ULONG XRight = PlainTextLow32;
/* Initialise blowfish */
ReturnCode = BLOWFISH_Init ( &Context, Key, KeyLength, BLOWFISH_MODE_ECB, 0, 0 );
_BLOWFISH_PrintReturnCode ( "BLOWFISH_Init", ReturnCode );
/* Print key information */
_BLOWFISH_PrintMode ( BLOWFISH_MODE_ECB );
_BLOWFISH_PrintBuffer ( "Key", Key, KeyLength );
if ( ReturnCode == BLOWFISH_RC_SUCCESS )
{
/* Encipher the 8-byte block of plaintext */
BLOWFISH_Encipher ( &Context, &XLeft, &XRight );
printf ( "Plaintext=0x%08x%08x (8 bytes)\n", (unsigned int)PlainTextHigh32, (unsigned int)PlainTextLow32 );
/* Is the ciphertext as expected? */
if ( XLeft == CipherTextHigh32 && XRight == CipherTextLow32 )
{
/* Decipher the ciphertext */
BLOWFISH_Decipher ( &Context, &XLeft, &XRight );
printf ( "Ciphertext=0x%08x%08x (8 bytes)\n", (unsigned int)CipherTextHigh32, (unsigned int)CipherTextLow32 );
/* Is the plaintext as expected? */
if ( XLeft != PlainTextHigh32 && XRight != PlainTextLow32 )
{
/* Failed to decipher properly */
_BLOWFISH_PrintReturnCode ( "BLOWFISH_Decipher", BLOWFISH_RC_TEST_FAILED );
printf ( "Invalid plaintext=0x%08x%08x (8 bytes)\n", (unsigned int)XLeft, (unsigned int)XRight );
ReturnCode = BLOWFISH_RC_TEST_FAILED;
}
}
else
{
/* Failed to encipher properly */
_BLOWFISH_PrintReturnCode ( "BLOWFISH_Encipher", BLOWFISH_RC_TEST_FAILED );
printf ( "Ciperhtext=0x%08x%08x (8 bytes)\nInvalid ciphertext=0x%08x%08x (8 bytes)\n", (unsigned int)CipherTextHigh32, (unsigned int)CipherTextLow32, (unsigned int)XLeft, (unsigned int)XRight );
ReturnCode = BLOWFISH_RC_TEST_FAILED;
}
}
printf ( "\n" );
/* Overwrite the blowfish context record */
BLOWFISH_Exit ( &Context );
return ReturnCode;
}
/**
@internal
Perform a CBC/CFB/OFB mode test on a buffer of data, and verify results.
@param Key Pointer to a buffer containing the key to use for cipher operations.
@param KeyLength Length of the key buffer.
@param Mode Mode with which to run the test. Must be either #BLOWFISH_MODE_CBC, #BLOWFISH_MODE_CFB or #BLOWFISH_MODE_OFB.
@param PlainTextBuffer Pointer to a buffer of plaintext to encipher.
@param CipherTextBuffer Pointer to a buffer of expected ciphertext.
@param BufferLength Length of the buffers.
@remarks For use with test vector 3.
@return #BLOWFISH_RC_SUCCESS Test passed successfully.
@return Specific return code, see #BLOWFISH_RC.
*/
static BLOWFISH_RC _BLOWFISH_Test_CBC_CFB_OFB ( BLOWFISH_PUCHAR Key, BLOWFISH_ULONG KeyLength, BLOWFISH_MODE Mode, BLOWFISH_PUCHAR PlainTextBuffer, BLOWFISH_PUCHAR CipherTextBuffer, BLOWFISH_ULONG BufferLength )
{
BLOWFISH_RC ReturnCode = BLOWFISH_RC_SUCCESS;
BLOWFISH_CONTEXT Context;
BLOWFISH_PUCHAR Buffer = 0;
/* Initialise blowfish */
ReturnCode = BLOWFISH_Init ( &Context, Key, KeyLength, Mode, _BLOWFISH_Tv3Iv [ 0 ], _BLOWFISH_Tv3Iv [ 1 ] );
_BLOWFISH_PrintReturnCode ( "BLOWFISH_Init", ReturnCode );
/* Print key information */
_BLOWFISH_PrintMode ( Mode );
_BLOWFISH_PrintBuffer ( "Key", Key, KeyLength );
_BLOWFISH_PrintBuffer ( "Initialisation vector", (BLOWFISH_PUCHAR)_BLOWFISH_Tv3Iv, 8 );
if ( ReturnCode == BLOWFISH_RC_SUCCESS )
{
Buffer = (BLOWFISH_PUCHAR)malloc ( BufferLength );
if ( Buffer != 0 )
{
/* Encipher the plaintext buffer */
ReturnCode = BLOWFISH_EncipherBuffer ( &Context, PlainTextBuffer, Buffer, BufferLength );
_BLOWFISH_PrintReturnCode ( "BLOWFISH_EncipherBuffer", ReturnCode );
_BLOWFISH_PrintBuffer ( "Plaintext", PlainTextBuffer, BufferLength );
if ( ReturnCode == BLOWFISH_RC_SUCCESS )
{
/* Is the ciphertext as expected? */
if ( memcmp ( CipherTextBuffer, Buffer, BufferLength ) == 0 )
{
/* Decipher the ciphertext buffer */
ReturnCode = BLOWFISH_DecipherBuffer ( &Context, CipherTextBuffer, Buffer, BufferLength );
_BLOWFISH_PrintReturnCode ( "BLOWFISH_DecipherBuffer", ReturnCode );
_BLOWFISH_PrintBuffer ( "Ciphertext", CipherTextBuffer, BufferLength );
if ( ReturnCode == BLOWFISH_RC_SUCCESS )
{
/* Is the plaintext as expected? */
if ( memcmp ( PlainTextBuffer, Buffer, BufferLength ) != 0 )
{
/* Failed to decipher properly */
_BLOWFISH_PrintBuffer ( "Invalid plaintext", Buffer, BufferLength );
ReturnCode = BLOWFISH_RC_TEST_FAILED;
}
}
}
else
{
/* Failed to encipher properly */
_BLOWFISH_PrintBuffer ( "Ciphertext", CipherTextBuffer, BufferLength );
_BLOWFISH_PrintBuffer ( "Invalid ciphertext", Buffer, BufferLength );
ReturnCode = BLOWFISH_RC_TEST_FAILED;
}
}
free ( Buffer );
}
}
printf ( "\n" );
/* Overwrite the blowfish context record */
BLOWFISH_Exit ( &Context );
return ReturnCode;
}
/**
@internal
Perform a stream based throughput test for the selected mode.
@param Mode Mode to use for the test.
@param StreamBlockSize Size of each chunk of the stream.
@remarks Enciphers/deciphers data as a stream for #_BLOWFISH_THROUGHPUT_DURATION seconds, and then calculates the throughput.
@return #BLOWFISH_RC_SUCCESS Test passed successfully.
@return Specific return code, see #BLOWFISH_RC.
*/
static BLOWFISH_RC _BLOWFISH_Test_Throughput ( BLOWFISH_MODE Mode, BLOWFISH_ULONG StreamBlockSize )
{
BLOWFISH_RC ReturnCode = BLOWFISH_RC_SUCCESS;
BLOWFISH_CONTEXT EncipherContext;
BLOWFISH_CONTEXT DecipherContext;
BLOWFISH_PUCHAR PlainTextBuffer = 0;
BLOWFISH_PUCHAR CipherTextBuffer = 0;
BLOWFISH_SIZE_T i = 0;
BLOWFISH_SIZE_T j = 0;
BLOWFISH_ULONG Sum = 0;
clock_t StartTime = 0;
clock_t EndTime = 0;
clock_t ElapsedEncipherTime = 0;
clock_t ElapsedDecipherTime = 0;
float BlocksProcessed = 0;
#ifdef _OPENMP
BLOWFISH_SIZE_T Threads = omp_get_max_threads ( );
#else
BLOWFISH_SIZE_T Threads = 1;
#endif
/* Initialise blowfish for the encipher stream */
ReturnCode = BLOWFISH_Init ( &EncipherContext, (BLOWFISH_PUCHAR)"0123456789abcdef", 16, Mode, _BLOWFISH_Tv3Iv [ 0 ], _BLOWFISH_Tv3Iv [ 1 ] );
_BLOWFISH_PrintReturnCode ( "BLOWFISH_Init", ReturnCode );
_BLOWFISH_PrintMode ( Mode );
printf ( "Key=\"0123456789abcdef\"\n" );
if ( Mode != BLOWFISH_MODE_ECB )
{
_BLOWFISH_PrintBuffer ( "Initialisation vector", (BLOWFISH_PUCHAR)_BLOWFISH_Tv3Iv, 8 );
}
if ( ReturnCode == BLOWFISH_RC_SUCCESS )
{
/* Clone the context for the decipher stream */
ReturnCode = BLOWFISH_CloneContext ( &EncipherContext, &DecipherContext );
_BLOWFISH_PrintReturnCode ( "BLOWFISH_CloneContext", ReturnCode );
if ( ReturnCode == BLOWFISH_RC_SUCCESS )
{
/* Allocate the plaintext buffer */
PlainTextBuffer = (BLOWFISH_PUCHAR)malloc ( StreamBlockSize );
if ( PlainTextBuffer != 0 )
{
/* Allocate the ciphertext buffer */
CipherTextBuffer = (BLOWFISH_PUCHAR)malloc ( StreamBlockSize );
if ( CipherTextBuffer != 0 )
{
/* Create original plaintext buffer (use 0x01 for ease of vectorised verification) */
memset ( PlainTextBuffer, 0x01, StreamBlockSize );
/* Begin the stream for enciphering */
ReturnCode = BLOWFISH_BeginStream ( &EncipherContext );
_BLOWFISH_PrintReturnCode ( "BLOWFISH_BeginStream", ReturnCode );
if ( ReturnCode == BLOWFISH_RC_SUCCESS )
{
/* Begin the stream for deciphering */
ReturnCode = BLOWFISH_BeginStream ( &DecipherContext );
_BLOWFISH_PrintReturnCode ( "BLOWFISH_BeginStream", ReturnCode );
if ( ReturnCode == BLOWFISH_RC_SUCCESS )
{
/* While the total elapsed time (in seconds) has not passed the duration threshold, keep enciphering/deciphering the stream */
for ( i = 0; ( ( ElapsedEncipherTime + ElapsedDecipherTime ) / Threads ) / CLOCKS_PER_SEC <= _BLOWFISH_THROUGHPUT_DURATION; i++ )
{
/* Clear the ciphertext buffer */
memset ( CipherTextBuffer, 0x00, StreamBlockSize );
/* Encipher the plaintext */
StartTime = clock ( );
ReturnCode = BLOWFISH_EncipherStream ( &EncipherContext, PlainTextBuffer, CipherTextBuffer, StreamBlockSize );
EndTime = clock ( );
/* Compute the time elapsed enciphering (in milliseconds) */
ElapsedEncipherTime += ( EndTime - StartTime );
if ( ReturnCode != BLOWFISH_RC_SUCCESS )
{
_BLOWFISH_PrintReturnCode ( "BLOWFISH_EncipherStream", ReturnCode );
break;
}
/* Clear the plaintext buffer */
memset ( PlainTextBuffer, 0x00, StreamBlockSize );
/* Decipher the ciphertext */
StartTime = clock ( );
ReturnCode = BLOWFISH_DecipherStream ( &DecipherContext, CipherTextBuffer, PlainTextBuffer, StreamBlockSize );
EndTime = clock ( );
/* Compute the time elapsed deciphering (in milliseconds) */
ElapsedDecipherTime += ( EndTime - StartTime );
if ( ReturnCode != BLOWFISH_RC_SUCCESS )
{
_BLOWFISH_PrintReturnCode ( "BLOWFISH_DecipherStream", ReturnCode );
break;
}
/* Verify the integrity of the deciphered plaintext (sum of all bytes should equal the buffer length) */
for ( j = 0, Sum = 0; j < (BLOWFISH_SIZE_T)StreamBlockSize; j++ )
{
Sum += PlainTextBuffer [ j ];
}
if ( Sum != StreamBlockSize )
{
printf ( "BLOWFISH_EncipherStream()/BLOWFISH_DecipherStream()=Integrity check failed!\n" );
ReturnCode = BLOWFISH_RC_TEST_FAILED;
break;
}
}
if ( ReturnCode == BLOWFISH_RC_SUCCESS )
{
/* Ensure we managed to encipher/decipher enough data to determine the throughput in MB/s */
if ( ( i * StreamBlockSize ) > ( 1024 * 1024 ) )
{
/* Adjust elapsed time based on thread count */
ElapsedEncipherTime = ElapsedEncipherTime / Threads;
ElapsedDecipherTime = ElapsedDecipherTime / Threads;
/* Convert elapsed time from milliseconds to seconds (minimum 1 second) */
ElapsedEncipherTime = ElapsedEncipherTime / CLOCKS_PER_SEC > 1 ? ElapsedEncipherTime / CLOCKS_PER_SEC : 1;
ElapsedDecipherTime = ElapsedDecipherTime / CLOCKS_PER_SEC > 1 ? ElapsedDecipherTime / CLOCKS_PER_SEC : 1;
/* Calculate and display the stream length */
BlocksProcessed = (float)( (float)( i * StreamBlockSize ) / ( 1024 * 1024 ) );
printf ( "Stream length=%0.2f MB (%d*%d byte blocks)\n", BlocksProcessed, (int)i, (int)StreamBlockSize );
/* Calculate and display throughputs */
printf ( "Encipher throughput=%0.2f MB/s\n", BlocksProcessed / ElapsedEncipherTime );
printf ( "Decipher throughput=%0.2f MB/s\n", BlocksProcessed / ElapsedDecipherTime );
printf ( "Average throughput=%0.2f MB/s\n", ( ( BlocksProcessed / ElapsedDecipherTime ) + ( BlocksProcessed / ElapsedEncipherTime ) ) / 2 );
}
else
{
printf ( "Failed to process enough data to determine throughput in MB/s!\n" );
ReturnCode = BLOWFISH_RC_TEST_FAILED;
}
}
/* Finished decipering */
BLOWFISH_EndStream ( &DecipherContext );
}
/* Finished encipering */
BLOWFISH_EndStream ( &EncipherContext );
}
/* Free the ciphertext */
free ( CipherTextBuffer );
}
/* Free the plaintext */
free ( PlainTextBuffer );
}
}
/* Overwrite the deciper stream context record */
BLOWFISH_Exit ( &DecipherContext );
}
printf ( "\n" );
/* Overwrite the encipher stream context record */
BLOWFISH_Exit ( &EncipherContext );
return ReturnCode;
}
/**
@internal
Perform all self-tests for all supported modes.
@return #BLOWFISH_RC_SUCCESS All tests passed successfully.
@return Specific return code, see #BLOWFISH_RC.
*/
static BLOWFISH_RC _BLOWFISH_SelfTest ( )
{
BLOWFISH_RC ReturnCode;
BLOWFISH_ULONG i = 0;
printf ( "Standard test vectors...\n\n" );
/* Perform ECB mode tests on test vector 1 */
for ( i = 0; i < sizeof ( _BLOWFISH_EcbTv1 ) / sizeof ( _BLOWFISH_EcbTv1 [ 0 ] ); i++ )
{
ReturnCode = _BLOWFISH_Test_ECB ( (BLOWFISH_PUCHAR)&_BLOWFISH_EcbTv1 [ i ].Key, 8, _BLOWFISH_EcbTv1 [ i ].PlainText [ 0 ], _BLOWFISH_EcbTv1 [ i ].PlainText [ 1 ], _BLOWFISH_EcbTv1 [ i ].CipherText [ 0 ], _BLOWFISH_EcbTv1 [ i ].CipherText [ 1 ] );
if ( ReturnCode != BLOWFISH_RC_SUCCESS )
{
return ReturnCode;
}
}
/* Perform ECB mode tests on test vector 2 */
for ( i = 0; i < sizeof ( _BLOWFISH_EcbTv2CipherText ) / sizeof ( _BLOWFISH_EcbTv2CipherText [ 0 ] ); i++ )
{
ReturnCode = _BLOWFISH_Test_ECB ( (BLOWFISH_PUCHAR)&_BLOWFISH_EcbTv2Key, i + 4, _BLOWFISH_EcbTv2PlainText [ 0 ], _BLOWFISH_EcbTv2PlainText [ 1 ], _BLOWFISH_EcbTv2CipherText [ i ] [ 0 ], _BLOWFISH_EcbTv2CipherText [ i ] [ 1 ] );
if ( ReturnCode != BLOWFISH_RC_SUCCESS )
{
return ReturnCode;
}
}
/* Perform CBC, CFB and OFB tests on test vector 3 */
for ( i = 0; i < sizeof ( _BLOWFISH_Tv3Mode ) / sizeof ( _BLOWFISH_Tv3Mode [ 0 ] ); i++ )
{
ReturnCode = _BLOWFISH_Test_CBC_CFB_OFB ( (BLOWFISH_PUCHAR)&_BLOWFISH_Tv3Key, sizeof ( _BLOWFISH_Tv3Key ), _BLOWFISH_Tv3Mode [ i ], (BLOWFISH_PUCHAR)&_BLOWFISH_Tv3PlainText, (BLOWFISH_PUCHAR)&_BLOWFISH_Tv3CipherText [ i ], sizeof ( _BLOWFISH_Tv3PlainText ) );
if ( ReturnCode != BLOWFISH_RC_SUCCESS )
{
return ReturnCode;
}
}
#ifdef _OPENMP
/* Perform parallelised throughput tests if there is more than 1 available thread */
if ( omp_get_max_threads ( ) > 1 )
{
printf ( "Parallelised throughput tests (using %d threads for ~%d seconds per mode)...\n\n", omp_get_max_threads ( ), _BLOWFISH_THROUGHPUT_DURATION );
for ( i = 0; i < sizeof ( _BLOWFISH_ThroughputTv ) / sizeof ( _BLOWFISH_ThroughputTv [ 0 ] ); i++ )
{
if ( _BLOWFISH_ThroughputTv [ i ].Parallel != 0x00 )
{
ReturnCode = _BLOWFISH_Test_Throughput ( _BLOWFISH_ThroughputTv [ i ].Mode, _BLOWFISH_THROUGHPUT_STREAM_LENGTH );
if ( ReturnCode != BLOWFISH_RC_SUCCESS )
{
return ReturnCode;
}
}
}
}
/* Use a single thread for the serialised tests */
omp_set_num_threads ( 1 );
#endif
/* Perform serialised throughput tests */
printf ( "Serialised throughput tests (using 1 thread for ~%d seconds per mode)...\n\n", _BLOWFISH_THROUGHPUT_DURATION );
for ( i = 0; i < sizeof ( _BLOWFISH_ThroughputTv ) / sizeof ( _BLOWFISH_ThroughputTv [ 0 ] ); i++ )
{
ReturnCode = _BLOWFISH_Test_Throughput ( _BLOWFISH_ThroughputTv [ i ].Mode, _BLOWFISH_THROUGHPUT_STREAM_LENGTH );
if ( ReturnCode != BLOWFISH_RC_SUCCESS )
{
return ReturnCode;
}
}
return BLOWFISH_RC_SUCCESS;
}
/**
@internal
Main entry point for the blowfish self-test application.
@param ArgumentCount Number of command line arguments passed to the application.
@param ArgumentVector Array of command line arguments passed to the application.
@return #BLOWFISH_RC_SUCCESS All tests passed successfully.
@return Specific return code, see #BLOWFISH_RC.
*/
int main ( int ArgumentCount, char * ArgumentVector [ ] )
{
BLOWFISH_RC ReturnCode;
/* Unreferenced parameters */
ArgumentCount = ArgumentCount;
ArgumentVector = ArgumentVector;
/* Perform all self tests */
printf ( "Blowfish selft-test application.\nCopyright (c) 2008, Tom Bonner (tom.bonner@gmail.com)\n\n(For best results close all running applications)\n\n" );
ReturnCode = _BLOWFISH_SelfTest ( );
if ( ReturnCode == BLOWFISH_RC_SUCCESS )
{
/* All self test passed successfully */
printf ( "All Blowfish self-tests passed successfully!\n" );
}
else
{
/* One of the self tests failed */
printf ( "Blowfish self-test failed!\n" );
}
return (int)ReturnCode;
}
/** @} */

View file

@ -0,0 +1,17 @@
cmake_minimum_required(VERSION 3.12)
project(tiny-aes C)
add_library(${PROJECT_NAME} "")
target_sources(${PROJECT_NAME}
PRIVATE
${CMAKE_CURRENT_LIST_DIR}/aes.c
INTERFACE
${CMAKE_CURRENT_LIST_DIR}/aes.h
${CMAKE_CURRENT_LIST_DIR}/aes.hpp
)
target_include_directories(${PROJECT_NAME}
INTERFACE
${CMAKE_CURRENT_LIST_DIR}
)

61
shared/thirdparty/tiny-AES-c/Makefile vendored Normal file
View file

@ -0,0 +1,61 @@
#CC = avr-gcc
#CFLAGS = -Wall -mmcu=atmega16 -Os -Wl,-Map,test.map
#OBJCOPY = avr-objcopy
CC = gcc
LD = gcc
AR = ar
ARFLAGS = rcs
CFLAGS = -Wall -Os -c
LDFLAGS = -Wall -Os -Wl,-Map,test.map
ifdef AES192
CFLAGS += -DAES192=1
endif
ifdef AES256
CFLAGS += -DAES256=1
endif
OBJCOPYFLAGS = -j .text -O ihex
OBJCOPY = objcopy
# include path to AVR library
INCLUDE_PATH = /usr/lib/avr/include
# splint static check
SPLINT = splint test.c aes.c -I$(INCLUDE_PATH) +charindex -unrecog
default: test.elf
.SILENT:
.PHONY: lint clean
test.hex : test.elf
echo copy object-code to new image and format in hex
$(OBJCOPY) ${OBJCOPYFLAGS} $< $@
test.o : test.c aes.h aes.o
echo [CC] $@ $(CFLAGS)
$(CC) $(CFLAGS) -o $@ $<
aes.o : aes.c aes.h
echo [CC] $@ $(CFLAGS)
$(CC) $(CFLAGS) -o $@ $<
test.elf : aes.o test.o
echo [LD] $@
$(LD) $(LDFLAGS) -o $@ $^
aes.a : aes.o
echo [AR] $@
$(AR) $(ARFLAGS) $@ $^
lib : aes.a
clean:
rm -f *.OBJ *.LST *.o *.gch *.out *.hex *.map *.elf *.a
test:
make clean && make && ./test.elf
make clean && make AES192=1 && ./test.elf
make clean && make AES256=1 && ./test.elf
lint:
$(call SPLINT)

83
shared/thirdparty/tiny-AES-c/README.md vendored Normal file
View file

@ -0,0 +1,83 @@
![CI](https://github.com/kokke/tiny-AES-c/workflows/CI/badge.svg)
### Tiny AES in C
This is a small and portable implementation of the AES [ECB](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_Codebook_.28ECB.29), [CTR](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_.28CTR.29) and [CBC](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29) encryption algorithms written in C.
You can override the default key-size of 128 bit with 192 or 256 bit by defining the symbols AES192 or AES256 in [`aes.h`](https://github.com/kokke/tiny-AES-c/blob/master/aes.h).
The API is very simple and looks like this (I am using C99 `<stdint.h>`-style annotated types):
```C
/* Initialize context calling one of: */
void AES_init_ctx(struct AES_ctx* ctx, const uint8_t* key);
void AES_init_ctx_iv(struct AES_ctx* ctx, const uint8_t* key, const uint8_t* iv);
/* ... or reset IV at random point: */
void AES_ctx_set_iv(struct AES_ctx* ctx, const uint8_t* iv);
/* Then start encrypting and decrypting with the functions below: */
void AES_ECB_encrypt(const struct AES_ctx* ctx, uint8_t* buf);
void AES_ECB_decrypt(const struct AES_ctx* ctx, uint8_t* buf);
void AES_CBC_encrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length);
void AES_CBC_decrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length);
/* Same function for encrypting as for decrypting in CTR mode */
void AES_CTR_xcrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length);
```
Important notes:
* No padding is provided so for CBC and ECB all buffers should be multiples of 16 bytes. For padding [PKCS7](https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS7) is recommendable.
* ECB mode is considered unsafe for most uses and is not implemented in streaming mode. If you need this mode, call the function for every block of 16 bytes you need encrypted. See [wikipedia's article on ECB](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_Codebook_(ECB)) for more details.
* This library is designed for small code size and simplicity, intended for cases where small binary size, low memory footprint and portability is more important than high performance. If speed is a concern, you can try more complex libraries, e.g. [Mbed TLS](https://tls.mbed.org/), [OpenSSL](https://www.openssl.org/) etc.
You can choose to use any or all of the modes-of-operations, by defining the symbols CBC, CTR or ECB in [`aes.h`](https://github.com/kokke/tiny-AES-c/blob/master/aes.h) (read the comments for clarification).
C++ users should `#include` [aes.hpp](https://github.com/kokke/tiny-AES-c/blob/master/aes.hpp) instead of [aes.h](https://github.com/kokke/tiny-AES-c/blob/master/aes.h)
There is no built-in error checking or protection from out-of-bounds memory access errors as a result of malicious input.
The module uses less than 200 bytes of RAM and 1-2K ROM when compiled for ARM, but YMMV depending on which modes are enabled.
It is one of the smallest implementations in C I've seen yet, but do contact me if you know of something smaller (or have improvements to the code here).
I've successfully used the code on 64bit x86, 32bit ARM and 8 bit AVR platforms.
GCC size output when only CTR mode is compiled for ARM:
$ arm-none-eabi-gcc -Os -DCBC=0 -DECB=0 -DCTR=1 -c aes.c
$ size aes.o
text data bss dec hex filename
1171 0 0 1171 493 aes.o
.. and when compiling for the THUMB instruction set, we end up well below 1K in code size.
$ arm-none-eabi-gcc -Os -mthumb -DCBC=0 -DECB=0 -DCTR=1 -c aes.c
$ size aes.o
text data bss dec hex filename
903 0 0 903 387 aes.o
I am using the Free Software Foundation, ARM GCC compiler:
$ arm-none-eabi-gcc --version
arm-none-eabi-gcc (4.8.4-1+11-1) 4.8.4 20141219 (release)
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
This implementation is verified against the data in:
[National Institute of Standards and Technology Special Publication 800-38A 2001 ED](http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38a.pdf) Appendix F: Example Vectors for Modes of Operation of the AES.
The other appendices in the document are valuable for implementation details on e.g. padding, generation of IVs and nonces in CTR-mode etc.
A heartfelt thank-you to [all the nice people](https://github.com/kokke/tiny-AES-c/graphs/contributors) out there who have contributed to this project.
All material in this repository is in the public domain.

572
shared/thirdparty/tiny-AES-c/aes.c vendored Normal file
View file

@ -0,0 +1,572 @@
/*
This is an implementation of the AES algorithm, specifically ECB, CTR and CBC mode.
Block size can be chosen in aes.h - available choices are AES128, AES192, AES256.
The implementation is verified against the test vectors in:
National Institute of Standards and Technology Special Publication 800-38A 2001 ED
ECB-AES128
----------
plain-text:
6bc1bee22e409f96e93d7e117393172a
ae2d8a571e03ac9c9eb76fac45af8e51
30c81c46a35ce411e5fbc1191a0a52ef
f69f2445df4f9b17ad2b417be66c3710
key:
2b7e151628aed2a6abf7158809cf4f3c
resulting cipher
3ad77bb40d7a3660a89ecaf32466ef97
f5d3d58503b9699de785895a96fdbaaf
43b1cd7f598ece23881b00e3ed030688
7b0c785e27e8ad3f8223207104725dd4
NOTE: String length must be evenly divisible by 16byte (str_len % 16 == 0)
You should pad the end of the string with zeros if this is not the case.
For AES192/256 the key size is proportionally larger.
*/
/*****************************************************************************/
/* Includes: */
/*****************************************************************************/
#include <string.h> // CBC mode, for memset
#include "aes.h"
/*****************************************************************************/
/* Defines: */
/*****************************************************************************/
// The number of columns comprising a state in AES. This is a constant in AES. Value=4
#define Nb 4
#if defined(AES256) && (AES256 == 1)
#define Nk 8
#define Nr 14
#elif defined(AES192) && (AES192 == 1)
#define Nk 6
#define Nr 12
#else
#define Nk 4 // The number of 32 bit words in a key.
#define Nr 10 // The number of rounds in AES Cipher.
#endif
// jcallan@github points out that declaring Multiply as a function
// reduces code size considerably with the Keil ARM compiler.
// See this link for more information: https://github.com/kokke/tiny-AES-C/pull/3
#ifndef MULTIPLY_AS_A_FUNCTION
#define MULTIPLY_AS_A_FUNCTION 0
#endif
/*****************************************************************************/
/* Private variables: */
/*****************************************************************************/
// state - array holding the intermediate results during decryption.
typedef uint8_t state_t[4][4];
// The lookup-tables are marked const so they can be placed in read-only storage instead of RAM
// The numbers below can be computed dynamically trading ROM for RAM -
// This can be useful in (embedded) bootloader applications, where ROM is often limited.
static const uint8_t sbox[256] = {
//0 1 2 3 4 5 6 7 8 9 A B C D E F
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 };
#if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1)
static const uint8_t rsbox[256] = {
0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d };
#endif
// The round constant word array, Rcon[i], contains the values given by
// x to the power (i-1) being powers of x (x is denoted as {02}) in the field GF(2^8)
static const uint8_t Rcon[11] = {
0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36 };
/*
* Jordan Goulder points out in PR #12 (https://github.com/kokke/tiny-AES-C/pull/12),
* that you can remove most of the elements in the Rcon array, because they are unused.
*
* From Wikipedia's article on the Rijndael key schedule @ https://en.wikipedia.org/wiki/Rijndael_key_schedule#Rcon
*
* "Only the first some of these constants are actually used up to rcon[10] for AES-128 (as 11 round keys are needed),
* up to rcon[8] for AES-192, up to rcon[7] for AES-256. rcon[0] is not used in AES algorithm."
*/
/*****************************************************************************/
/* Private functions: */
/*****************************************************************************/
/*
static uint8_t getSBoxValue(uint8_t num)
{
return sbox[num];
}
*/
#define getSBoxValue(num) (sbox[(num)])
// This function produces Nb(Nr+1) round keys. The round keys are used in each round to decrypt the states.
static void KeyExpansion(uint8_t* RoundKey, const uint8_t* Key)
{
unsigned i, j, k;
uint8_t tempa[4]; // Used for the column/row operations
// The first round key is the key itself.
for (i = 0; i < Nk; ++i)
{
RoundKey[(i * 4) + 0] = Key[(i * 4) + 0];
RoundKey[(i * 4) + 1] = Key[(i * 4) + 1];
RoundKey[(i * 4) + 2] = Key[(i * 4) + 2];
RoundKey[(i * 4) + 3] = Key[(i * 4) + 3];
}
// All other round keys are found from the previous round keys.
for (i = Nk; i < Nb * (Nr + 1); ++i)
{
{
k = (i - 1) * 4;
tempa[0]=RoundKey[k + 0];
tempa[1]=RoundKey[k + 1];
tempa[2]=RoundKey[k + 2];
tempa[3]=RoundKey[k + 3];
}
if (i % Nk == 0)
{
// This function shifts the 4 bytes in a word to the left once.
// [a0,a1,a2,a3] becomes [a1,a2,a3,a0]
// Function RotWord()
{
const uint8_t u8tmp = tempa[0];
tempa[0] = tempa[1];
tempa[1] = tempa[2];
tempa[2] = tempa[3];
tempa[3] = u8tmp;
}
// SubWord() is a function that takes a four-byte input word and
// applies the S-box to each of the four bytes to produce an output word.
// Function Subword()
{
tempa[0] = getSBoxValue(tempa[0]);
tempa[1] = getSBoxValue(tempa[1]);
tempa[2] = getSBoxValue(tempa[2]);
tempa[3] = getSBoxValue(tempa[3]);
}
tempa[0] = tempa[0] ^ Rcon[i/Nk];
}
#if defined(AES256) && (AES256 == 1)
if (i % Nk == 4)
{
// Function Subword()
{
tempa[0] = getSBoxValue(tempa[0]);
tempa[1] = getSBoxValue(tempa[1]);
tempa[2] = getSBoxValue(tempa[2]);
tempa[3] = getSBoxValue(tempa[3]);
}
}
#endif
j = i * 4; k=(i - Nk) * 4;
RoundKey[j + 0] = RoundKey[k + 0] ^ tempa[0];
RoundKey[j + 1] = RoundKey[k + 1] ^ tempa[1];
RoundKey[j + 2] = RoundKey[k + 2] ^ tempa[2];
RoundKey[j + 3] = RoundKey[k + 3] ^ tempa[3];
}
}
void AES_init_ctx(struct AES_ctx* ctx, const uint8_t* key)
{
KeyExpansion(ctx->RoundKey, key);
}
#if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1))
void AES_init_ctx_iv(struct AES_ctx* ctx, const uint8_t* key, const uint8_t* iv)
{
KeyExpansion(ctx->RoundKey, key);
memcpy (ctx->Iv, iv, AES_BLOCKLEN);
}
void AES_ctx_set_iv(struct AES_ctx* ctx, const uint8_t* iv)
{
memcpy (ctx->Iv, iv, AES_BLOCKLEN);
}
#endif
// This function adds the round key to state.
// The round key is added to the state by an XOR function.
static void AddRoundKey(uint8_t round, state_t* state, const uint8_t* RoundKey)
{
uint8_t i,j;
for (i = 0; i < 4; ++i)
{
for (j = 0; j < 4; ++j)
{
(*state)[i][j] ^= RoundKey[(round * Nb * 4) + (i * Nb) + j];
}
}
}
// The SubBytes Function Substitutes the values in the
// state matrix with values in an S-box.
static void SubBytes(state_t* state)
{
uint8_t i, j;
for (i = 0; i < 4; ++i)
{
for (j = 0; j < 4; ++j)
{
(*state)[j][i] = getSBoxValue((*state)[j][i]);
}
}
}
// The ShiftRows() function shifts the rows in the state to the left.
// Each row is shifted with different offset.
// Offset = Row number. So the first row is not shifted.
static void ShiftRows(state_t* state)
{
uint8_t temp;
// Rotate first row 1 columns to left
temp = (*state)[0][1];
(*state)[0][1] = (*state)[1][1];
(*state)[1][1] = (*state)[2][1];
(*state)[2][1] = (*state)[3][1];
(*state)[3][1] = temp;
// Rotate second row 2 columns to left
temp = (*state)[0][2];
(*state)[0][2] = (*state)[2][2];
(*state)[2][2] = temp;
temp = (*state)[1][2];
(*state)[1][2] = (*state)[3][2];
(*state)[3][2] = temp;
// Rotate third row 3 columns to left
temp = (*state)[0][3];
(*state)[0][3] = (*state)[3][3];
(*state)[3][3] = (*state)[2][3];
(*state)[2][3] = (*state)[1][3];
(*state)[1][3] = temp;
}
static uint8_t xtime(uint8_t x)
{
return ((x<<1) ^ (((x>>7) & 1) * 0x1b));
}
// MixColumns function mixes the columns of the state matrix
static void MixColumns(state_t* state)
{
uint8_t i;
uint8_t Tmp, Tm, t;
for (i = 0; i < 4; ++i)
{
t = (*state)[i][0];
Tmp = (*state)[i][0] ^ (*state)[i][1] ^ (*state)[i][2] ^ (*state)[i][3] ;
Tm = (*state)[i][0] ^ (*state)[i][1] ; Tm = xtime(Tm); (*state)[i][0] ^= Tm ^ Tmp ;
Tm = (*state)[i][1] ^ (*state)[i][2] ; Tm = xtime(Tm); (*state)[i][1] ^= Tm ^ Tmp ;
Tm = (*state)[i][2] ^ (*state)[i][3] ; Tm = xtime(Tm); (*state)[i][2] ^= Tm ^ Tmp ;
Tm = (*state)[i][3] ^ t ; Tm = xtime(Tm); (*state)[i][3] ^= Tm ^ Tmp ;
}
}
// Multiply is used to multiply numbers in the field GF(2^8)
// Note: The last call to xtime() is unneeded, but often ends up generating a smaller binary
// The compiler seems to be able to vectorize the operation better this way.
// See https://github.com/kokke/tiny-AES-c/pull/34
#if MULTIPLY_AS_A_FUNCTION
static uint8_t Multiply(uint8_t x, uint8_t y)
{
return (((y & 1) * x) ^
((y>>1 & 1) * xtime(x)) ^
((y>>2 & 1) * xtime(xtime(x))) ^
((y>>3 & 1) * xtime(xtime(xtime(x)))) ^
((y>>4 & 1) * xtime(xtime(xtime(xtime(x)))))); /* this last call to xtime() can be omitted */
}
#else
#define Multiply(x, y) \
( ((y & 1) * x) ^ \
((y>>1 & 1) * xtime(x)) ^ \
((y>>2 & 1) * xtime(xtime(x))) ^ \
((y>>3 & 1) * xtime(xtime(xtime(x)))) ^ \
((y>>4 & 1) * xtime(xtime(xtime(xtime(x)))))) \
#endif
#if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1)
/*
static uint8_t getSBoxInvert(uint8_t num)
{
return rsbox[num];
}
*/
#define getSBoxInvert(num) (rsbox[(num)])
// MixColumns function mixes the columns of the state matrix.
// The method used to multiply may be difficult to understand for the inexperienced.
// Please use the references to gain more information.
static void InvMixColumns(state_t* state)
{
int i;
uint8_t a, b, c, d;
for (i = 0; i < 4; ++i)
{
a = (*state)[i][0];
b = (*state)[i][1];
c = (*state)[i][2];
d = (*state)[i][3];
(*state)[i][0] = Multiply(a, 0x0e) ^ Multiply(b, 0x0b) ^ Multiply(c, 0x0d) ^ Multiply(d, 0x09);
(*state)[i][1] = Multiply(a, 0x09) ^ Multiply(b, 0x0e) ^ Multiply(c, 0x0b) ^ Multiply(d, 0x0d);
(*state)[i][2] = Multiply(a, 0x0d) ^ Multiply(b, 0x09) ^ Multiply(c, 0x0e) ^ Multiply(d, 0x0b);
(*state)[i][3] = Multiply(a, 0x0b) ^ Multiply(b, 0x0d) ^ Multiply(c, 0x09) ^ Multiply(d, 0x0e);
}
}
// The SubBytes Function Substitutes the values in the
// state matrix with values in an S-box.
static void InvSubBytes(state_t* state)
{
uint8_t i, j;
for (i = 0; i < 4; ++i)
{
for (j = 0; j < 4; ++j)
{
(*state)[j][i] = getSBoxInvert((*state)[j][i]);
}
}
}
static void InvShiftRows(state_t* state)
{
uint8_t temp;
// Rotate first row 1 columns to right
temp = (*state)[3][1];
(*state)[3][1] = (*state)[2][1];
(*state)[2][1] = (*state)[1][1];
(*state)[1][1] = (*state)[0][1];
(*state)[0][1] = temp;
// Rotate second row 2 columns to right
temp = (*state)[0][2];
(*state)[0][2] = (*state)[2][2];
(*state)[2][2] = temp;
temp = (*state)[1][2];
(*state)[1][2] = (*state)[3][2];
(*state)[3][2] = temp;
// Rotate third row 3 columns to right
temp = (*state)[0][3];
(*state)[0][3] = (*state)[1][3];
(*state)[1][3] = (*state)[2][3];
(*state)[2][3] = (*state)[3][3];
(*state)[3][3] = temp;
}
#endif // #if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1)
// Cipher is the main function that encrypts the PlainText.
static void Cipher(state_t* state, const uint8_t* RoundKey)
{
uint8_t round = 0;
// Add the First round key to the state before starting the rounds.
AddRoundKey(0, state, RoundKey);
// There will be Nr rounds.
// The first Nr-1 rounds are identical.
// These Nr rounds are executed in the loop below.
// Last one without MixColumns()
for (round = 1; ; ++round)
{
SubBytes(state);
ShiftRows(state);
if (round == Nr) {
break;
}
MixColumns(state);
AddRoundKey(round, state, RoundKey);
}
// Add round key to last round
AddRoundKey(Nr, state, RoundKey);
}
#if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1)
static void InvCipher(state_t* state, const uint8_t* RoundKey)
{
uint8_t round = 0;
// Add the First round key to the state before starting the rounds.
AddRoundKey(Nr, state, RoundKey);
// There will be Nr rounds.
// The first Nr-1 rounds are identical.
// These Nr rounds are executed in the loop below.
// Last one without InvMixColumn()
for (round = (Nr - 1); ; --round)
{
InvShiftRows(state);
InvSubBytes(state);
AddRoundKey(round, state, RoundKey);
if (round == 0) {
break;
}
InvMixColumns(state);
}
}
#endif // #if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1)
/*****************************************************************************/
/* Public functions: */
/*****************************************************************************/
#if defined(ECB) && (ECB == 1)
void AES_ECB_encrypt(const struct AES_ctx* ctx, uint8_t* buf)
{
// The next function call encrypts the PlainText with the Key using AES algorithm.
Cipher((state_t*)buf, ctx->RoundKey);
}
void AES_ECB_decrypt(const struct AES_ctx* ctx, uint8_t* buf)
{
// The next function call decrypts the PlainText with the Key using AES algorithm.
InvCipher((state_t*)buf, ctx->RoundKey);
}
#endif // #if defined(ECB) && (ECB == 1)
#if defined(CBC) && (CBC == 1)
static void XorWithIv(uint8_t* buf, const uint8_t* Iv)
{
uint8_t i;
for (i = 0; i < AES_BLOCKLEN; ++i) // The block in AES is always 128bit no matter the key size
{
buf[i] ^= Iv[i];
}
}
void AES_CBC_encrypt_buffer(struct AES_ctx *ctx, uint8_t* buf, size_t length)
{
size_t i;
uint8_t *Iv = ctx->Iv;
for (i = 0; i < length; i += AES_BLOCKLEN)
{
XorWithIv(buf, Iv);
Cipher((state_t*)buf, ctx->RoundKey);
Iv = buf;
buf += AES_BLOCKLEN;
}
/* store Iv in ctx for next call */
memcpy(ctx->Iv, Iv, AES_BLOCKLEN);
}
void AES_CBC_decrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length)
{
size_t i;
uint8_t storeNextIv[AES_BLOCKLEN];
for (i = 0; i < length; i += AES_BLOCKLEN)
{
memcpy(storeNextIv, buf, AES_BLOCKLEN);
InvCipher((state_t*)buf, ctx->RoundKey);
XorWithIv(buf, ctx->Iv);
memcpy(ctx->Iv, storeNextIv, AES_BLOCKLEN);
buf += AES_BLOCKLEN;
}
}
#endif // #if defined(CBC) && (CBC == 1)
#if defined(CTR) && (CTR == 1)
/* Symmetrical operation: same function for encrypting as for decrypting. Note any IV/nonce should never be reused with the same key */
void AES_CTR_xcrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length)
{
uint8_t buffer[AES_BLOCKLEN];
size_t i;
int bi;
for (i = 0, bi = AES_BLOCKLEN; i < length; ++i, ++bi)
{
if (bi == AES_BLOCKLEN) /* we need to regen xor compliment in buffer */
{
memcpy(buffer, ctx->Iv, AES_BLOCKLEN);
Cipher((state_t*)buffer,ctx->RoundKey);
/* Increment Iv and handle overflow */
for (bi = (AES_BLOCKLEN - 1); bi >= 0; --bi)
{
/* inc will overflow */
if (ctx->Iv[bi] == 255)
{
ctx->Iv[bi] = 0;
continue;
}
ctx->Iv[bi] += 1;
break;
}
bi = 0;
}
buf[i] = (buf[i] ^ buffer[bi]);
}
}
#endif // #if defined(CTR) && (CTR == 1)

91
shared/thirdparty/tiny-AES-c/aes.h vendored Normal file
View file

@ -0,0 +1,91 @@
#ifndef _AES_H_
#define _AES_H_
#include <stdint.h>
#include <stddef.h>
// #define the macros below to 1/0 to enable/disable the mode of operation.
//
// CBC enables AES encryption in CBC-mode of operation.
// CTR enables encryption in counter-mode.
// ECB enables the basic ECB 16-byte block algorithm. All can be enabled simultaneously.
// The #ifndef-guard allows it to be configured before #include'ing or at compile time.
#ifndef CBC
#define CBC 1
#endif
#ifndef ECB
#define ECB 1
#endif
#ifndef CTR
#define CTR 1
#endif
#define AES128 1
//#define AES192 1
//#define AES256 1
#define AES_BLOCKLEN 16 // Block length in bytes - AES is 128b block only
#if defined(AES256) && (AES256 == 1)
#define AES_KEYLEN 32
#define AES_keyExpSize 240
#elif defined(AES192) && (AES192 == 1)
#define AES_KEYLEN 24
#define AES_keyExpSize 208
#else
#define AES_KEYLEN 16 // Key length in bytes
#define AES_keyExpSize 176
#endif
struct AES_ctx
{
uint8_t RoundKey[AES_keyExpSize];
#if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1))
uint8_t Iv[AES_BLOCKLEN];
#endif
};
void AES_init_ctx(struct AES_ctx* ctx, const uint8_t* key);
#if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1))
void AES_init_ctx_iv(struct AES_ctx* ctx, const uint8_t* key, const uint8_t* iv);
void AES_ctx_set_iv(struct AES_ctx* ctx, const uint8_t* iv);
#endif
#if defined(ECB) && (ECB == 1)
// buffer size is exactly AES_BLOCKLEN bytes;
// you need only AES_init_ctx as IV is not used in ECB
// NB: ECB is considered insecure for most uses
void AES_ECB_encrypt(const struct AES_ctx* ctx, uint8_t* buf);
void AES_ECB_decrypt(const struct AES_ctx* ctx, uint8_t* buf);
#endif // #if defined(ECB) && (ECB == !)
#if defined(CBC) && (CBC == 1)
// buffer size MUST be mutile of AES_BLOCKLEN;
// Suggest https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS7 for padding scheme
// NOTES: you need to set IV in ctx via AES_init_ctx_iv() or AES_ctx_set_iv()
// no IV should ever be reused with the same key
void AES_CBC_encrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length);
void AES_CBC_decrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length);
#endif // #if defined(CBC) && (CBC == 1)
#if defined(CTR) && (CTR == 1)
// Same function for encrypting as for decrypting.
// IV is incremented for every block, and used after encryption as XOR-compliment for output
// Suggesting https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS7 for padding scheme
// NOTES: you need to set IV in ctx with AES_init_ctx_iv() or AES_ctx_set_iv()
// no IV should ever be reused with the same key
void AES_CTR_xcrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, size_t length);
#endif // #if defined(CTR) && (CTR == 1)
#endif // _AES_H_

12
shared/thirdparty/tiny-AES-c/aes.hpp vendored Normal file
View file

@ -0,0 +1,12 @@
#ifndef _AES_HPP_
#define _AES_HPP_
#ifndef __cplusplus
#error Do not include the hpp header in a c project!
#endif //__cplusplus
extern "C" {
#include "aes.h"
}
#endif //_AES_HPP_

View file

@ -0,0 +1,73 @@
from conans import ConanFile, CMake
from conans.errors import ConanException
class TinyAesCConan(ConanFile):
name = "tiny-AES-c"
version = "1.0.0"
license = "The Unlicense"
url = "https://github.com/kokke/tiny-AES-c"
description = "Small portable AES128/192/256 in C"
topics = ("encryption", "crypto", "AES")
settings = "os", "compiler", "build_type", "arch"
generators = "cmake"
exports_sources = ["CMakeLists.txt", "*.c", '*.h', '*.hpp']
exports = ["unlicense.txt"]
_options_dict = {
# enable AES128
"AES128": [True, False],
# enable AES192
"AES192": [True, False],
# enable AES256
"AES256": [True, False],
# enable AES encryption in CBC-mode of operation
"CBC": [True, False],
# enable the basic ECB 16-byte block algorithm
"ECB": [True, False],
# enable encryption in counter-mode
"CTR": [True, False],
}
options = _options_dict
default_options = {
"AES128": True,
"AES192": False,
"AES256": False,
"CBC": True,
"ECB": True,
"CTR": True
}
def configure(self):
if not self.options.CBC and not self.options.ECB and not self.options.CTR:
raise ConanException("Need to at least specify one of CBC, ECB or CTR modes")
if not self.options.AES128 and not self.options.AES192 and not self.options.AES256:
raise ConanException("Need to at least specify one of AES{128, 192, 256} modes")
def build(self):
cmake = CMake(self)
for key in self._options_dict.keys():
if self.options[key]:
cmake.definitions["CMAKE_CFLAGS"].append(key)
cmake.configure()
cmake.build()
def package(self):
self.copy("*.h", dst="include")
self.copy("*.hpp", dst="include")
self.copy("*.a", dst="lib", keep_path=False)
self.copy("unlicense.txt")
def package_info(self):
self.cpp_info.libs = ["tiny-aes"]

View file

@ -0,0 +1,13 @@
{
"name": "tiny-AES-c",
"keywords": "cryptography, aes",
"description": "Small portable AES128/192/256 in C",
"repository":
{
"type": "git",
"url": "https://github.com/kokke/tiny-AES-c.git"
},
"frameworks": "*",
"platforms": "*",
"examples": "test.c"
}

View file

@ -0,0 +1,11 @@
name=tiny-AES-c
version=1.0.0
author=kokke
maintainer=kokke
sentence=A small and portable implementation of the AES ECB, CTR and CBC encryption algorithms written in C.
paragraph=You can override the default key-size of 128 bit with 192 or 256 bit by defining the symbols AES192 or AES256 in aes.h. The API is very simple. No padding is provided so for CBC and ECB all buffers should be multiples of 16 bytes.
category=Data Processing
url=https://github.com/kokke/tiny-AES-c
repository=https://github.com/kokke/tiny-AES-c.git
architectures=*
includes=aes.h

316
shared/thirdparty/tiny-AES-c/test.C vendored Normal file
View file

@ -0,0 +1,316 @@
#include <stdio.h>
#include <string.h>
#include <stdint.h>
// Enable ECB, CTR and CBC mode. Note this can be done before including aes.h or at compile-time.
// E.g. with GCC by using the -D flag: gcc -c aes.c -DCBC=0 -DCTR=1 -DECB=1
#define CBC 1
#define CTR 1
#define ECB 1
#include "aes.h"
static void phex(uint8_t* str);
static int test_encrypt_cbc(void);
static int test_decrypt_cbc(void);
static int test_encrypt_ctr(void);
static int test_decrypt_ctr(void);
static int test_encrypt_ecb(void);
static int test_decrypt_ecb(void);
static void test_encrypt_ecb_verbose(void);
int main(void)
{
int exit;
#if defined(AES256)
printf("\nTesting AES256\n\n");
#elif defined(AES192)
printf("\nTesting AES192\n\n");
#elif defined(AES128)
printf("\nTesting AES128\n\n");
#else
printf("You need to specify a symbol between AES128, AES192 or AES256. Exiting");
return 0;
#endif
exit = test_encrypt_cbc() + test_decrypt_cbc() +
test_encrypt_ctr() + test_decrypt_ctr() +
test_decrypt_ecb() + test_encrypt_ecb();
test_encrypt_ecb_verbose();
return exit;
}
// prints string as hex
static void phex(uint8_t* str)
{
#if defined(AES256)
uint8_t len = 32;
#elif defined(AES192)
uint8_t len = 24;
#elif defined(AES128)
uint8_t len = 16;
#endif
unsigned char i;
for (i = 0; i < len; ++i)
printf("%.2x", str[i]);
printf("\n");
}
static void test_encrypt_ecb_verbose(void)
{
// Example of more verbose verification
uint8_t i;
// 128bit key
uint8_t key[16] = { (uint8_t) 0x2b, (uint8_t) 0x7e, (uint8_t) 0x15, (uint8_t) 0x16, (uint8_t) 0x28, (uint8_t) 0xae, (uint8_t) 0xd2, (uint8_t) 0xa6, (uint8_t) 0xab, (uint8_t) 0xf7, (uint8_t) 0x15, (uint8_t) 0x88, (uint8_t) 0x09, (uint8_t) 0xcf, (uint8_t) 0x4f, (uint8_t) 0x3c };
// 512bit text
uint8_t plain_text[64] = { (uint8_t) 0x6b, (uint8_t) 0xc1, (uint8_t) 0xbe, (uint8_t) 0xe2, (uint8_t) 0x2e, (uint8_t) 0x40, (uint8_t) 0x9f, (uint8_t) 0x96, (uint8_t) 0xe9, (uint8_t) 0x3d, (uint8_t) 0x7e, (uint8_t) 0x11, (uint8_t) 0x73, (uint8_t) 0x93, (uint8_t) 0x17, (uint8_t) 0x2a,
(uint8_t) 0xae, (uint8_t) 0x2d, (uint8_t) 0x8a, (uint8_t) 0x57, (uint8_t) 0x1e, (uint8_t) 0x03, (uint8_t) 0xac, (uint8_t) 0x9c, (uint8_t) 0x9e, (uint8_t) 0xb7, (uint8_t) 0x6f, (uint8_t) 0xac, (uint8_t) 0x45, (uint8_t) 0xaf, (uint8_t) 0x8e, (uint8_t) 0x51,
(uint8_t) 0x30, (uint8_t) 0xc8, (uint8_t) 0x1c, (uint8_t) 0x46, (uint8_t) 0xa3, (uint8_t) 0x5c, (uint8_t) 0xe4, (uint8_t) 0x11, (uint8_t) 0xe5, (uint8_t) 0xfb, (uint8_t) 0xc1, (uint8_t) 0x19, (uint8_t) 0x1a, (uint8_t) 0x0a, (uint8_t) 0x52, (uint8_t) 0xef,
(uint8_t) 0xf6, (uint8_t) 0x9f, (uint8_t) 0x24, (uint8_t) 0x45, (uint8_t) 0xdf, (uint8_t) 0x4f, (uint8_t) 0x9b, (uint8_t) 0x17, (uint8_t) 0xad, (uint8_t) 0x2b, (uint8_t) 0x41, (uint8_t) 0x7b, (uint8_t) 0xe6, (uint8_t) 0x6c, (uint8_t) 0x37, (uint8_t) 0x10 };
// print text to encrypt, key and IV
printf("ECB encrypt verbose:\n\n");
printf("plain text:\n");
for (i = (uint8_t) 0; i < (uint8_t) 4; ++i)
{
phex(plain_text + i * (uint8_t) 16);
}
printf("\n");
printf("key:\n");
phex(key);
printf("\n");
// print the resulting cipher as 4 x 16 byte strings
printf("ciphertext:\n");
struct AES_ctx ctx;
AES_init_ctx(&ctx, key);
for (i = 0; i < 4; ++i)
{
AES_ECB_encrypt(&ctx, plain_text + (i * 16));
phex(plain_text + (i * 16));
}
printf("\n");
}
static int test_encrypt_ecb(void)
{
#if defined(AES256)
uint8_t key[] = { 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81,
0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4 };
uint8_t out[] = { 0xf3, 0xee, 0xd1, 0xbd, 0xb5, 0xd2, 0xa0, 0x3c, 0x06, 0x4b, 0x5a, 0x7e, 0x3d, 0xb1, 0x81, 0xf8 };
#elif defined(AES192)
uint8_t key[] = { 0x8e, 0x73, 0xb0, 0xf7, 0xda, 0x0e, 0x64, 0x52, 0xc8, 0x10, 0xf3, 0x2b, 0x80, 0x90, 0x79, 0xe5,
0x62, 0xf8, 0xea, 0xd2, 0x52, 0x2c, 0x6b, 0x7b };
uint8_t out[] = { 0xbd, 0x33, 0x4f, 0x1d, 0x6e, 0x45, 0xf2, 0x5f, 0xf7, 0x12, 0xa2, 0x14, 0x57, 0x1f, 0xa5, 0xcc };
#elif defined(AES128)
uint8_t key[] = { 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c };
uint8_t out[] = { 0x3a, 0xd7, 0x7b, 0xb4, 0x0d, 0x7a, 0x36, 0x60, 0xa8, 0x9e, 0xca, 0xf3, 0x24, 0x66, 0xef, 0x97 };
#endif
uint8_t in[] = { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a };
struct AES_ctx ctx;
AES_init_ctx(&ctx, key);
AES_ECB_encrypt(&ctx, in);
printf("ECB encrypt: ");
if (0 == memcmp((char*) out, (char*) in, 16)) {
printf("SUCCESS!\n");
return(0);
} else {
printf("FAILURE!\n");
return(1);
}
}
static int test_decrypt_cbc(void)
{
#if defined(AES256)
uint8_t key[] = { 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81,
0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4 };
uint8_t in[] = { 0xf5, 0x8c, 0x4c, 0x04, 0xd6, 0xe5, 0xf1, 0xba, 0x77, 0x9e, 0xab, 0xfb, 0x5f, 0x7b, 0xfb, 0xd6,
0x9c, 0xfc, 0x4e, 0x96, 0x7e, 0xdb, 0x80, 0x8d, 0x67, 0x9f, 0x77, 0x7b, 0xc6, 0x70, 0x2c, 0x7d,
0x39, 0xf2, 0x33, 0x69, 0xa9, 0xd9, 0xba, 0xcf, 0xa5, 0x30, 0xe2, 0x63, 0x04, 0x23, 0x14, 0x61,
0xb2, 0xeb, 0x05, 0xe2, 0xc3, 0x9b, 0xe9, 0xfc, 0xda, 0x6c, 0x19, 0x07, 0x8c, 0x6a, 0x9d, 0x1b };
#elif defined(AES192)
uint8_t key[] = { 0x8e, 0x73, 0xb0, 0xf7, 0xda, 0x0e, 0x64, 0x52, 0xc8, 0x10, 0xf3, 0x2b, 0x80, 0x90, 0x79, 0xe5, 0x62, 0xf8, 0xea, 0xd2, 0x52, 0x2c, 0x6b, 0x7b };
uint8_t in[] = { 0x4f, 0x02, 0x1d, 0xb2, 0x43, 0xbc, 0x63, 0x3d, 0x71, 0x78, 0x18, 0x3a, 0x9f, 0xa0, 0x71, 0xe8,
0xb4, 0xd9, 0xad, 0xa9, 0xad, 0x7d, 0xed, 0xf4, 0xe5, 0xe7, 0x38, 0x76, 0x3f, 0x69, 0x14, 0x5a,
0x57, 0x1b, 0x24, 0x20, 0x12, 0xfb, 0x7a, 0xe0, 0x7f, 0xa9, 0xba, 0xac, 0x3d, 0xf1, 0x02, 0xe0,
0x08, 0xb0, 0xe2, 0x79, 0x88, 0x59, 0x88, 0x81, 0xd9, 0x20, 0xa9, 0xe6, 0x4f, 0x56, 0x15, 0xcd };
#elif defined(AES128)
uint8_t key[] = { 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c };
uint8_t in[] = { 0x76, 0x49, 0xab, 0xac, 0x81, 0x19, 0xb2, 0x46, 0xce, 0xe9, 0x8e, 0x9b, 0x12, 0xe9, 0x19, 0x7d,
0x50, 0x86, 0xcb, 0x9b, 0x50, 0x72, 0x19, 0xee, 0x95, 0xdb, 0x11, 0x3a, 0x91, 0x76, 0x78, 0xb2,
0x73, 0xbe, 0xd6, 0xb8, 0xe3, 0xc1, 0x74, 0x3b, 0x71, 0x16, 0xe6, 0x9e, 0x22, 0x22, 0x95, 0x16,
0x3f, 0xf1, 0xca, 0xa1, 0x68, 0x1f, 0xac, 0x09, 0x12, 0x0e, 0xca, 0x30, 0x75, 0x86, 0xe1, 0xa7 };
#endif
uint8_t iv[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
uint8_t out[] = { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a,
0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51,
0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef,
0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10 };
// uint8_t buffer[64];
struct AES_ctx ctx;
AES_init_ctx_iv(&ctx, key, iv);
AES_CBC_decrypt_buffer(&ctx, in, 64);
printf("CBC decrypt: ");
if (0 == memcmp((char*) out, (char*) in, 64)) {
printf("SUCCESS!\n");
return(0);
} else {
printf("FAILURE!\n");
return(1);
}
}
static int test_encrypt_cbc(void)
{
#if defined(AES256)
uint8_t key[] = { 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81,
0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4 };
uint8_t out[] = { 0xf5, 0x8c, 0x4c, 0x04, 0xd6, 0xe5, 0xf1, 0xba, 0x77, 0x9e, 0xab, 0xfb, 0x5f, 0x7b, 0xfb, 0xd6,
0x9c, 0xfc, 0x4e, 0x96, 0x7e, 0xdb, 0x80, 0x8d, 0x67, 0x9f, 0x77, 0x7b, 0xc6, 0x70, 0x2c, 0x7d,
0x39, 0xf2, 0x33, 0x69, 0xa9, 0xd9, 0xba, 0xcf, 0xa5, 0x30, 0xe2, 0x63, 0x04, 0x23, 0x14, 0x61,
0xb2, 0xeb, 0x05, 0xe2, 0xc3, 0x9b, 0xe9, 0xfc, 0xda, 0x6c, 0x19, 0x07, 0x8c, 0x6a, 0x9d, 0x1b };
#elif defined(AES192)
uint8_t key[] = { 0x8e, 0x73, 0xb0, 0xf7, 0xda, 0x0e, 0x64, 0x52, 0xc8, 0x10, 0xf3, 0x2b, 0x80, 0x90, 0x79, 0xe5, 0x62, 0xf8, 0xea, 0xd2, 0x52, 0x2c, 0x6b, 0x7b };
uint8_t out[] = { 0x4f, 0x02, 0x1d, 0xb2, 0x43, 0xbc, 0x63, 0x3d, 0x71, 0x78, 0x18, 0x3a, 0x9f, 0xa0, 0x71, 0xe8,
0xb4, 0xd9, 0xad, 0xa9, 0xad, 0x7d, 0xed, 0xf4, 0xe5, 0xe7, 0x38, 0x76, 0x3f, 0x69, 0x14, 0x5a,
0x57, 0x1b, 0x24, 0x20, 0x12, 0xfb, 0x7a, 0xe0, 0x7f, 0xa9, 0xba, 0xac, 0x3d, 0xf1, 0x02, 0xe0,
0x08, 0xb0, 0xe2, 0x79, 0x88, 0x59, 0x88, 0x81, 0xd9, 0x20, 0xa9, 0xe6, 0x4f, 0x56, 0x15, 0xcd };
#elif defined(AES128)
uint8_t key[] = { 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c };
uint8_t out[] = { 0x76, 0x49, 0xab, 0xac, 0x81, 0x19, 0xb2, 0x46, 0xce, 0xe9, 0x8e, 0x9b, 0x12, 0xe9, 0x19, 0x7d,
0x50, 0x86, 0xcb, 0x9b, 0x50, 0x72, 0x19, 0xee, 0x95, 0xdb, 0x11, 0x3a, 0x91, 0x76, 0x78, 0xb2,
0x73, 0xbe, 0xd6, 0xb8, 0xe3, 0xc1, 0x74, 0x3b, 0x71, 0x16, 0xe6, 0x9e, 0x22, 0x22, 0x95, 0x16,
0x3f, 0xf1, 0xca, 0xa1, 0x68, 0x1f, 0xac, 0x09, 0x12, 0x0e, 0xca, 0x30, 0x75, 0x86, 0xe1, 0xa7 };
#endif
uint8_t iv[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
uint8_t in[] = { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a,
0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51,
0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef,
0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10 };
struct AES_ctx ctx;
AES_init_ctx_iv(&ctx, key, iv);
AES_CBC_encrypt_buffer(&ctx, in, 64);
printf("CBC encrypt: ");
if (0 == memcmp((char*) out, (char*) in, 64)) {
printf("SUCCESS!\n");
return(0);
} else {
printf("FAILURE!\n");
return(1);
}
}
static int test_xcrypt_ctr(const char* xcrypt);
static int test_encrypt_ctr(void)
{
return test_xcrypt_ctr("encrypt");
}
static int test_decrypt_ctr(void)
{
return test_xcrypt_ctr("decrypt");
}
static int test_xcrypt_ctr(const char* xcrypt)
{
#if defined(AES256)
uint8_t key[32] = { 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81,
0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4 };
uint8_t in[64] = { 0x60, 0x1e, 0xc3, 0x13, 0x77, 0x57, 0x89, 0xa5, 0xb7, 0xa7, 0xf5, 0x04, 0xbb, 0xf3, 0xd2, 0x28,
0xf4, 0x43, 0xe3, 0xca, 0x4d, 0x62, 0xb5, 0x9a, 0xca, 0x84, 0xe9, 0x90, 0xca, 0xca, 0xf5, 0xc5,
0x2b, 0x09, 0x30, 0xda, 0xa2, 0x3d, 0xe9, 0x4c, 0xe8, 0x70, 0x17, 0xba, 0x2d, 0x84, 0x98, 0x8d,
0xdf, 0xc9, 0xc5, 0x8d, 0xb6, 0x7a, 0xad, 0xa6, 0x13, 0xc2, 0xdd, 0x08, 0x45, 0x79, 0x41, 0xa6 };
#elif defined(AES192)
uint8_t key[24] = { 0x8e, 0x73, 0xb0, 0xf7, 0xda, 0x0e, 0x64, 0x52, 0xc8, 0x10, 0xf3, 0x2b, 0x80, 0x90, 0x79, 0xe5,
0x62, 0xf8, 0xea, 0xd2, 0x52, 0x2c, 0x6b, 0x7b };
uint8_t in[64] = { 0x1a, 0xbc, 0x93, 0x24, 0x17, 0x52, 0x1c, 0xa2, 0x4f, 0x2b, 0x04, 0x59, 0xfe, 0x7e, 0x6e, 0x0b,
0x09, 0x03, 0x39, 0xec, 0x0a, 0xa6, 0xfa, 0xef, 0xd5, 0xcc, 0xc2, 0xc6, 0xf4, 0xce, 0x8e, 0x94,
0x1e, 0x36, 0xb2, 0x6b, 0xd1, 0xeb, 0xc6, 0x70, 0xd1, 0xbd, 0x1d, 0x66, 0x56, 0x20, 0xab, 0xf7,
0x4f, 0x78, 0xa7, 0xf6, 0xd2, 0x98, 0x09, 0x58, 0x5a, 0x97, 0xda, 0xec, 0x58, 0xc6, 0xb0, 0x50 };
#elif defined(AES128)
uint8_t key[16] = { 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c };
uint8_t in[64] = { 0x87, 0x4d, 0x61, 0x91, 0xb6, 0x20, 0xe3, 0x26, 0x1b, 0xef, 0x68, 0x64, 0x99, 0x0d, 0xb6, 0xce,
0x98, 0x06, 0xf6, 0x6b, 0x79, 0x70, 0xfd, 0xff, 0x86, 0x17, 0x18, 0x7b, 0xb9, 0xff, 0xfd, 0xff,
0x5a, 0xe4, 0xdf, 0x3e, 0xdb, 0xd5, 0xd3, 0x5e, 0x5b, 0x4f, 0x09, 0x02, 0x0d, 0xb0, 0x3e, 0xab,
0x1e, 0x03, 0x1d, 0xda, 0x2f, 0xbe, 0x03, 0xd1, 0x79, 0x21, 0x70, 0xa0, 0xf3, 0x00, 0x9c, 0xee };
#endif
uint8_t iv[16] = { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff };
uint8_t out[64] = { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a,
0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51,
0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef,
0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10 };
struct AES_ctx ctx;
AES_init_ctx_iv(&ctx, key, iv);
AES_CTR_xcrypt_buffer(&ctx, in, 64);
printf("CTR %s: ", xcrypt);
if (0 == memcmp((char *) out, (char *) in, 64)) {
printf("SUCCESS!\n");
return(0);
} else {
printf("FAILURE!\n");
return(1);
}
}
static int test_decrypt_ecb(void)
{
#if defined(AES256)
uint8_t key[] = { 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81,
0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4 };
uint8_t in[] = { 0xf3, 0xee, 0xd1, 0xbd, 0xb5, 0xd2, 0xa0, 0x3c, 0x06, 0x4b, 0x5a, 0x7e, 0x3d, 0xb1, 0x81, 0xf8 };
#elif defined(AES192)
uint8_t key[] = { 0x8e, 0x73, 0xb0, 0xf7, 0xda, 0x0e, 0x64, 0x52, 0xc8, 0x10, 0xf3, 0x2b, 0x80, 0x90, 0x79, 0xe5,
0x62, 0xf8, 0xea, 0xd2, 0x52, 0x2c, 0x6b, 0x7b };
uint8_t in[] = { 0xbd, 0x33, 0x4f, 0x1d, 0x6e, 0x45, 0xf2, 0x5f, 0xf7, 0x12, 0xa2, 0x14, 0x57, 0x1f, 0xa5, 0xcc };
#elif defined(AES128)
uint8_t key[] = { 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c };
uint8_t in[] = { 0x3a, 0xd7, 0x7b, 0xb4, 0x0d, 0x7a, 0x36, 0x60, 0xa8, 0x9e, 0xca, 0xf3, 0x24, 0x66, 0xef, 0x97 };
#endif
uint8_t out[] = { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a };
struct AES_ctx ctx;
AES_init_ctx(&ctx, key);
AES_ECB_decrypt(&ctx, in);
printf("ECB decrypt: ");
if (0 == memcmp((char*) out, (char*) in, 16)) {
printf("SUCCESS!\n");
return(0);
} else {
printf("FAILURE!\n");
return(1);
}
}

2
shared/thirdparty/tiny-AES-c/test.cpp vendored Normal file
View file

@ -0,0 +1,2 @@
#include "aes.hpp"
#include "test.c"

View file

@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 2.8.12)
project(TinyAesPackageTest C CXX)
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
conan_basic_setup()
add_executable(example ../test.c)
add_executable(example_cpp ../test.cpp)
target_link_libraries(example ${CONAN_LIBS})
target_link_libraries(example_cpp ${CONAN_LIBS})

View file

@ -0,0 +1,17 @@
from conans import ConanFile, CMake, tools
import os
class TinyAesCTestConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
generators = "cmake"
def build(self):
cmake = CMake(self)
cmake.configure()
cmake.build()
def test(self):
if not tools.cross_building(self.settings):
os.chdir("bin")
self.run(".%sexample" % os.sep)

View file

@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>

View file

@ -0,0 +1,32 @@
CC = gcc
NOVAPROVA_CFLAGS= $(shell pkg-config --cflags novaprova)
NOVAPROVA_LIBS= $(shell pkg-config --libs novaprova)
CFLAGS = -Wall -g $(NOVAPROVA_CFLAGS)
OBJCOPY = objcopy
# splint static check
SPLINT = splint test.c aes.c +charindex -unrecog
.SILENT:
.PHONY: lint clean
CODE_SOURCE= aes.c pkcs7_padding.c sha1.c
CODE_OBJS= $(CODE_SOURCE:.c=.o)
TEST_SOURCE= test/aes.c test/pkcs7_padding.c test/sha1.c
TEST_OBJS= $(TEST_SOURCE:.c=.o)
testrunner: $(TEST_OBJS) $(CODE_OBJS)
$(LINK.c) -o $@ $(TEST_OBJS) $(CODE_OBJS) $(NOVAPROVA_LIBS)
clean:
rm testrunner $(CODE_OBJS) $(TEST_OBJS)
lint:
$(call SPLINT)
test: testrunner
./testrunner

View file

@ -0,0 +1,73 @@
### Tiny AES128 in C
This is a small and portable implementation of the AES128 ECB and CBC encryption algorithms written in C.
The API is very simple and looks like this (I am using C99 `<stdint.h>`-style annotated types):
```C
void AES128_ECB_encrypt(uint8_t* input, const uint8_t* key, uint8_t* output);
void AES128_ECB_decrypt(uint8_t* input, const uint8_t* key, uint8_t* output);
void AES128_CBC_encrypt_buffer(uint8_t* output, uint8_t* input, uint32_t length, const uint8_t* key, const uint8_t* iv);
void AES128_CBC_decrypt_buffer(uint8_t* output, uint8_t* input, uint32_t length, const uint8_t* key, const uint8_t* iv);
```
You can choose to use one or both of the modes-of-operation, by defining the symbols CBC and ECB. See the header file for clarification.
Additionally, there are two variants of the CBC functions that operate on the buffer "in-place"
```C
uint8_t AES128_CBC_encrypt_inplace( uint8_t* data, size_t length, const uint8_t* key, const uint8_t* iv);
uint8_t AES128_CBC_decrypt_inplace( uint8_t* data, size_t length, const uint8_t* key, uint8_t* iv);
```
These have their own restrictions, see the header file for details.
The module uses around 200 bytes of RAM and 2.5K ROM when compiled for ARM (~2K for Thumb but YMMV).
It is the smallest implementation in C I've seen yet, but do contact me if you know of something smaller (or have improvements to the code here).
I've successfully used the code on 64bit x86, 32bit ARM and 8 bit AVR platforms.
GCC size output when ECB mode is compiled for ARM:
$ arm-none-eabi-gcc -Os -c aes.c -DCBC=0
$ size aes.o
text data bss dec hex filename
2323 0 184 2507 9cb aes.o
.. and when compiling for the THUMB instruction set, we end up around 2K in code size.
$ arm-none-eabi-gcc -mthumb -Os -c aes.c -DCBC=0
$ size aes.o
text data bss dec hex filename
1775 0 184 1959 7a7 aes.o
I am using Mentor Graphics free ARM toolchain:
$ arm-none-eabi-gcc --version
arm-none-eabi-gcc (GNU Tools for ARM Embedded Processors) 4.8.4 20140526 (release) [ARM/embedded-4_8-branch revision 211358]
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
This implementation is verified against the data in:
[National Institute of Standards and Technology Special Publication 800-38A 2001 ED](http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf) Appendix F: Example Vectors for Modes of Operation of the AES.
All material in this repository is in the public domain.
Modifications made to test using the [NovaProva C testing framework](http://novaprova.org/)

659
shared/thirdparty/tiny-AES128-C/aes.C vendored Normal file
View file

@ -0,0 +1,659 @@
/*
This is an implementation of the AES128 algorithm, specifically ECB and CBC mode.
The implementation is verified against the test vectors in:
National Institute of Standards and Technology Special Publication 800-38A 2001 ED
ECB-AES128
----------
plain-text:
6bc1bee22e409f96e93d7e117393172a
ae2d8a571e03ac9c9eb76fac45af8e51
30c81c46a35ce411e5fbc1191a0a52ef
f69f2445df4f9b17ad2b417be66c3710
key:
2b7e151628aed2a6abf7158809cf4f3c
resulting cipher
3ad77bb40d7a3660a89ecaf32466ef97
f5d3d58503b9699de785895a96fdbaaf
43b1cd7f598ece23881b00e3ed030688
7b0c785e27e8ad3f8223207104725dd4
NOTE: String length must be evenly divisible by 16byte (str_len % 16 == 0)
You should pad the end of the string with zeros if this is not the case.
*/
/*****************************************************************************/
/* Includes: */
/*****************************************************************************/
#include <stdint.h>
#include <string.h> // CBC mode, for memset
#include "aes.h"
/*****************************************************************************/
/* Defines: */
/*****************************************************************************/
// The number of columns comprising a state in AES. This is a constant in AES. Value=4
#define Nb 4
// The number of 32 bit words in a key.
#define Nk 4
// Key length in bytes [128 bit]
#define KEYLEN 16
// The number of rounds in AES Cipher.
#define Nr 10
// jcallan@github points out that declaring Multiply as a function
// reduces code size considerably with the Keil ARM compiler.
// See this link for more information: https://github.com/kokke/tiny-AES128-C/pull/3
#ifndef MULTIPLY_AS_A_FUNCTION
#define MULTIPLY_AS_A_FUNCTION 0
#endif
/*****************************************************************************/
/* Private variables: */
/*****************************************************************************/
// state - array holding the intermediate results during decryption.
typedef uint8_t state_t[4][4];
static state_t* state;
// The array that stores the round keys.
static uint8_t RoundKey[176];
// The Key input to the AES Program
static const uint8_t* Key;
#if defined(CBC) && CBC
// Initial Vector used only for CBC mode
static uint8_t* Iv;
#endif
// The lookup-tables are marked const so they can be placed in read-only storage instead of RAM
// The numbers below can be computed dynamically trading ROM for RAM -
// This can be useful in (embedded) bootloader applications, where ROM is often limited.
static const uint8_t sbox[256] = {
//0 1 2 3 4 5 6 7 8 9 A B C D E F
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 };
static const uint8_t rsbox[256] =
{ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d };
// The round constant word array, Rcon[i], contains the values given by
// x to th e power (i-1) being powers of x (x is denoted as {02}) in the field GF(2^8)
// Note that i starts at 1, not 0).
static const uint8_t Rcon[255] = {
0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39,
0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8,
0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef,
0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b,
0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3,
0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94,
0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20,
0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35,
0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f,
0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04,
0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63,
0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb };
/*****************************************************************************/
/* Private functions: */
/*****************************************************************************/
static uint8_t getSBoxValue(uint8_t num)
{
return sbox[num];
}
static uint8_t getSBoxInvert(uint8_t num)
{
return rsbox[num];
}
// This function produces Nb(Nr+1) round keys. The round keys are used in each round to decrypt the states.
static void KeyExpansion(void)
{
uint32_t i, j, k;
uint8_t tempa[4]; // Used for the column/row operations
// The first round key is the key itself.
for(i = 0; i < Nk; ++i)
{
RoundKey[(i * 4) + 0] = Key[(i * 4) + 0];
RoundKey[(i * 4) + 1] = Key[(i * 4) + 1];
RoundKey[(i * 4) + 2] = Key[(i * 4) + 2];
RoundKey[(i * 4) + 3] = Key[(i * 4) + 3];
}
// All other round keys are found from the previous round keys.
for(; (i < (Nb * (Nr + 1))); ++i)
{
for(j = 0; j < 4; ++j)
{
tempa[j]=RoundKey[(i-1) * 4 + j];
}
if (i % Nk == 0)
{
// This function rotates the 4 bytes in a word to the left once.
// [a0,a1,a2,a3] becomes [a1,a2,a3,a0]
// Function RotWord()
{
k = tempa[0];
tempa[0] = tempa[1];
tempa[1] = tempa[2];
tempa[2] = tempa[3];
tempa[3] = k;
}
// SubWord() is a function that takes a four-byte input word and
// applies the S-box to each of the four bytes to produce an output word.
// Function Subword()
{
tempa[0] = getSBoxValue(tempa[0]);
tempa[1] = getSBoxValue(tempa[1]);
tempa[2] = getSBoxValue(tempa[2]);
tempa[3] = getSBoxValue(tempa[3]);
}
tempa[0] = tempa[0] ^ Rcon[i/Nk];
}
else if (Nk > 6 && i % Nk == 4)
{
// Function Subword()
{
tempa[0] = getSBoxValue(tempa[0]);
tempa[1] = getSBoxValue(tempa[1]);
tempa[2] = getSBoxValue(tempa[2]);
tempa[3] = getSBoxValue(tempa[3]);
}
}
RoundKey[i * 4 + 0] = RoundKey[(i - Nk) * 4 + 0] ^ tempa[0];
RoundKey[i * 4 + 1] = RoundKey[(i - Nk) * 4 + 1] ^ tempa[1];
RoundKey[i * 4 + 2] = RoundKey[(i - Nk) * 4 + 2] ^ tempa[2];
RoundKey[i * 4 + 3] = RoundKey[(i - Nk) * 4 + 3] ^ tempa[3];
}
}
// This function adds the round key to state.
// The round key is added to the state by an XOR function.
static void AddRoundKey(uint8_t round)
{
uint8_t i,j;
for(i=0;i<4;++i)
{
for(j = 0; j < 4; ++j)
{
(*state)[i][j] ^= RoundKey[round * Nb * 4 + i * Nb + j];
}
}
}
// The SubBytes Function Substitutes the values in the
// state matrix with values in an S-box.
static void SubBytes(void)
{
uint8_t i, j;
for(i = 0; i < 4; ++i)
{
for(j = 0; j < 4; ++j)
{
(*state)[j][i] = getSBoxValue((*state)[j][i]);
}
}
}
// The ShiftRows() function shifts the rows in the state to the left.
// Each row is shifted with different offset.
// Offset = Row number. So the first row is not shifted.
static void ShiftRows(void)
{
uint8_t temp;
// Rotate first row 1 columns to left
temp = (*state)[0][1];
(*state)[0][1] = (*state)[1][1];
(*state)[1][1] = (*state)[2][1];
(*state)[2][1] = (*state)[3][1];
(*state)[3][1] = temp;
// Rotate second row 2 columns to left
temp = (*state)[0][2];
(*state)[0][2] = (*state)[2][2];
(*state)[2][2] = temp;
temp = (*state)[1][2];
(*state)[1][2] = (*state)[3][2];
(*state)[3][2] = temp;
// Rotate third row 3 columns to left
temp = (*state)[0][3];
(*state)[0][3] = (*state)[3][3];
(*state)[3][3] = (*state)[2][3];
(*state)[2][3] = (*state)[1][3];
(*state)[1][3] = temp;
}
static uint8_t xtime(uint8_t x)
{
return ((x<<1) ^ (((x>>7) & 1) * 0x1b));
}
// MixColumns function mixes the columns of the state matrix
static void MixColumns(void)
{
uint8_t i;
uint8_t Tmp,Tm,t;
for(i = 0; i < 4; ++i)
{
t = (*state)[i][0];
Tmp = (*state)[i][0] ^ (*state)[i][1] ^ (*state)[i][2] ^ (*state)[i][3] ;
Tm = (*state)[i][0] ^ (*state)[i][1] ; Tm = xtime(Tm); (*state)[i][0] ^= Tm ^ Tmp ;
Tm = (*state)[i][1] ^ (*state)[i][2] ; Tm = xtime(Tm); (*state)[i][1] ^= Tm ^ Tmp ;
Tm = (*state)[i][2] ^ (*state)[i][3] ; Tm = xtime(Tm); (*state)[i][2] ^= Tm ^ Tmp ;
Tm = (*state)[i][3] ^ t ; Tm = xtime(Tm); (*state)[i][3] ^= Tm ^ Tmp ;
}
}
// Multiply is used to multiply numbers in the field GF(2^8)
#if MULTIPLY_AS_A_FUNCTION
static uint8_t Multiply(uint8_t x, uint8_t y)
{
return (((y & 1) * x) ^
((y>>1 & 1) * xtime(x)) ^
((y>>2 & 1) * xtime(xtime(x))) ^
((y>>3 & 1) * xtime(xtime(xtime(x)))) ^
((y>>4 & 1) * xtime(xtime(xtime(xtime(x))))));
}
#else
#define Multiply(x, y) \
( ((y & 1) * x) ^ \
((y>>1 & 1) * xtime(x)) ^ \
((y>>2 & 1) * xtime(xtime(x))) ^ \
((y>>3 & 1) * xtime(xtime(xtime(x)))) ^ \
((y>>4 & 1) * xtime(xtime(xtime(xtime(x)))))) \
#endif
// MixColumns function mixes the columns of the state matrix.
// The method used to multiply may be difficult to understand for the inexperienced.
// Please use the references to gain more information.
static void InvMixColumns(void)
{
int i;
uint8_t a,b,c,d;
for(i=0;i<4;++i)
{
a = (*state)[i][0];
b = (*state)[i][1];
c = (*state)[i][2];
d = (*state)[i][3];
(*state)[i][0] = Multiply(a, 0x0e) ^ Multiply(b, 0x0b) ^ Multiply(c, 0x0d) ^ Multiply(d, 0x09);
(*state)[i][1] = Multiply(a, 0x09) ^ Multiply(b, 0x0e) ^ Multiply(c, 0x0b) ^ Multiply(d, 0x0d);
(*state)[i][2] = Multiply(a, 0x0d) ^ Multiply(b, 0x09) ^ Multiply(c, 0x0e) ^ Multiply(d, 0x0b);
(*state)[i][3] = Multiply(a, 0x0b) ^ Multiply(b, 0x0d) ^ Multiply(c, 0x09) ^ Multiply(d, 0x0e);
}
}
// The SubBytes Function Substitutes the values in the
// state matrix with values in an S-box.
static void InvSubBytes(void)
{
uint8_t i,j;
for(i=0;i<4;++i)
{
for(j=0;j<4;++j)
{
(*state)[j][i] = getSBoxInvert((*state)[j][i]);
}
}
}
static void InvShiftRows(void)
{
uint8_t temp;
// Rotate first row 1 columns to right
temp=(*state)[3][1];
(*state)[3][1]=(*state)[2][1];
(*state)[2][1]=(*state)[1][1];
(*state)[1][1]=(*state)[0][1];
(*state)[0][1]=temp;
// Rotate second row 2 columns to right
temp=(*state)[0][2];
(*state)[0][2]=(*state)[2][2];
(*state)[2][2]=temp;
temp=(*state)[1][2];
(*state)[1][2]=(*state)[3][2];
(*state)[3][2]=temp;
// Rotate third row 3 columns to right
temp=(*state)[0][3];
(*state)[0][3]=(*state)[1][3];
(*state)[1][3]=(*state)[2][3];
(*state)[2][3]=(*state)[3][3];
(*state)[3][3]=temp;
}
// Cipher is the main function that encrypts the PlainText.
static void Cipher(void)
{
uint8_t round = 0;
// Add the First round key to the state before starting the rounds.
AddRoundKey(0);
// There will be Nr rounds.
// The first Nr-1 rounds are identical.
// These Nr-1 rounds are executed in the loop below.
for(round = 1; round < Nr; ++round)
{
SubBytes();
ShiftRows();
MixColumns();
AddRoundKey(round);
}
// The last round is given below.
// The MixColumns function is not here in the last round.
SubBytes();
ShiftRows();
AddRoundKey(Nr);
}
static void InvCipher(void)
{
uint8_t round=0;
// Add the First round key to the state before starting the rounds.
AddRoundKey(Nr);
// There will be Nr rounds.
// The first Nr-1 rounds are identical.
// These Nr-1 rounds are executed in the loop below.
for(round=Nr-1;round>0;round--)
{
InvShiftRows();
InvSubBytes();
AddRoundKey(round);
InvMixColumns();
}
// The last round is given below.
// The MixColumns function is not here in the last round.
InvShiftRows();
InvSubBytes();
AddRoundKey(0);
}
static void BlockCopy(uint8_t* output, uint8_t* input)
{
uint8_t i;
for (i=0;i<KEYLEN;++i)
{
output[i] = input[i];
}
}
/*****************************************************************************/
/* Public functions: */
/*****************************************************************************/
#if defined(ECB) && ECB
void AES128_ECB_encrypt(uint8_t* input, const uint8_t* key, uint8_t* output)
{
// Copy input to output, and work in-memory on output
BlockCopy(output, input);
state = (state_t*)output;
Key = key;
KeyExpansion();
// The next function call encrypts the PlainText with the Key using AES algorithm.
Cipher();
}
void AES128_ECB_decrypt(uint8_t* input, const uint8_t* key, uint8_t *output)
{
// Copy input to output, and work in-memory on output
BlockCopy(output, input);
state = (state_t*)output;
// The KeyExpansion routine must be called before encryption.
Key = key;
KeyExpansion();
InvCipher();
}
#endif // #if defined(ECB) && ECB
#if defined(CBC) && CBC
static void XorWithIv(uint8_t* buf)
{
uint8_t i;
for(i = 0; i < KEYLEN; ++i)
{
buf[i] ^= Iv[i];
}
}
void AES128_CBC_encrypt_buffer(uint8_t* output, uint8_t* input, uint32_t length, const uint8_t* key, const uint8_t* iv)
{
size_t i;
uint8_t remainders = length % KEYLEN; /* Remaining bytes in the last non-full block */
BlockCopy(output, input);
state = (state_t*)output;
// Skip the key expansion if key is passed as 0
if(0 != key)
{
Key = key;
KeyExpansion();
}
if(iv != 0)
{
Iv = (uint8_t*)iv;
}
for(i = 0; i < length; i += KEYLEN)
{
XorWithIv(input);
BlockCopy(output, input);
state = (state_t*)output;
Cipher();
Iv = output;
input += KEYLEN;
output += KEYLEN;
}
if(remainders)
{
BlockCopy(output, input);
memset(output + remainders, 0, KEYLEN - remainders); /* add 0-padding */
state = (state_t*)output;
Cipher();
}
}
void AES128_CBC_decrypt_buffer(uint8_t* output, uint8_t* input, uint32_t length, const uint8_t* key, const uint8_t* iv)
{
size_t i;
uint8_t remainders = length % KEYLEN; /* Remaining bytes in the last non-full block */
BlockCopy(output, input);
state = (state_t*)output;
// Skip the key expansion if key is passed as 0
if(0 != key)
{
Key = key;
KeyExpansion();
}
// If iv is passed as 0, we continue to encrypt without re-setting the Iv
if(iv != 0)
{
Iv = (uint8_t*)iv;
}
for(i = 0; i < length; i += KEYLEN)
{
BlockCopy(output, input);
state = (state_t*)output;
InvCipher();
XorWithIv(output);
Iv = input;
input += KEYLEN;
output += KEYLEN;
}
if(remainders)
{
BlockCopy(output, input);
memset(output+remainders, 0, KEYLEN - remainders); /* add 0-padding */
state = (state_t*)output;
InvCipher();
}
}
uint8_t AES128_CBC_encrypt_inplace( uint8_t* data, size_t length, const uint8_t* key, const uint8_t* iv){
size_t i;
state = NULL;
/* Check for valid length. Must be > 0 and a multiple of KEYLEN */
if( length % KEYLEN != 0 || length == 0){
return 1;
}
// Skip the key expansion if key is passed as 0
if(0 != key)
{
Key = key;
KeyExpansion();
}
if(iv != 0)
{
Iv = (uint8_t*)iv;
}
for(i = 0; i < length; i += KEYLEN)
{
XorWithIv(data);
state = (state_t*)data;
Cipher();
Iv = data;
data += KEYLEN;
}
return 0;
}
/* We must have a writable iv pointer in this case, as we need the storage for holding the next decryption IV */
uint8_t AES128_CBC_decrypt_inplace( uint8_t* data, size_t length, const uint8_t* key, uint8_t* iv){
size_t i;
state = NULL;
uint8_t next_iv[KEYLEN];
/* Check for valid length. Must be > 0 and a multiple of KEYLEN */
if( length % KEYLEN != 0 || length == 0){
return 1;
}
if( 0 == iv )
{
return 2;
}
Iv = (uint8_t*)iv;
// Skip the key expansion if key is passed as 0
if(0 != key)
{
Key = key;
KeyExpansion();
}
BlockCopy(next_iv,data);
for(i = 0; i < length; i += KEYLEN)
{
state = (state_t*)data;
InvCipher();
XorWithIv(data);
data += KEYLEN;
/* use the last buffered IV */
BlockCopy(iv,next_iv);
/* and buffer the next */
BlockCopy(next_iv,data);
}
return 0;
}
#endif // #if defined(CBC) && CBC

49
shared/thirdparty/tiny-AES128-C/aes.H vendored Normal file
View file

@ -0,0 +1,49 @@
#ifndef _AES_H_
#define _AES_H_
#include <stdint.h>
// #define the macros below to 1/0 to enable/disable the mode of operation.
//
// CBC enables AES128 encryption in CBC-mode of operation and handles 0-padding.
// ECB enables the basic ECB 16-byte block algorithm. Both can be enabled simultaneously.
// The #ifndef-guard allows it to be configured before #include'ing or at compile time.
#ifndef CBC
#define CBC 1
#endif
#ifndef ECB
#define ECB 1
#endif
#if defined(ECB) && ECB
void AES128_ECB_encrypt(uint8_t* input, const uint8_t* key, uint8_t *output);
void AES128_ECB_decrypt(uint8_t* input, const uint8_t* key, uint8_t *output);
#endif // #if defined(ECB) && ECB
#if defined(CBC) && CBC
void AES128_CBC_encrypt_buffer(uint8_t* output, uint8_t* input, uint32_t length, const uint8_t* key, const uint8_t* iv);
void AES128_CBC_decrypt_buffer(uint8_t* output, uint8_t* input, uint32_t length, const uint8_t* key, const uint8_t* iv);
/* These variants encrypt and decrypt the data block in-place.
* The data block length MUST be a multiple of the algorithm block size (16 bytes)
* The return value will be non-zero if the length is incorrect.
* For the decypt function, the iv data must be writable, and will be modified on return.
*/
uint8_t AES128_CBC_encrypt_inplace( uint8_t* data, size_t length, const uint8_t* key, const uint8_t* iv);
uint8_t AES128_CBC_decrypt_inplace( uint8_t* data, size_t length, const uint8_t* key, uint8_t* iv);
#endif // #if defined(CBC) && CBC
#endif //_AES_H_

View file

@ -0,0 +1,56 @@
#include "pkcs7_padding.h"
int pkcs7_padding_pad_buffer( uint8_t *buffer, size_t data_length, size_t buffer_size, uint8_t modulus ){
uint8_t pad_byte = modulus - ( data_length % modulus ) ;
if( data_length + pad_byte > buffer_size ){
return -pad_byte;
}
int i = 0;
while( i < pad_byte){
buffer[data_length+i] = pad_byte;
i++;
}
return pad_byte;
}
int pkcs7_padding_valid( uint8_t *buffer, size_t data_length, size_t buffer_size, uint8_t modulus ){
uint8_t expected_pad_byte = modulus - ( data_length % modulus ) ;
if( data_length + expected_pad_byte > buffer_size ){
return 0;
}
int i = 0;
while( i < expected_pad_byte ){
if( buffer[data_length + i] != expected_pad_byte){
return 0;
}
i++;
}
return 1;
}
size_t pkcs7_padding_data_length( uint8_t * buffer, size_t buffer_size, uint8_t modulus ){
/* test for valid buffer size */
if( buffer_size % modulus != 0 ||
buffer_size < modulus ){
return 0;
}
uint8_t padding_value;
padding_value = buffer[buffer_size-1];
/* test for valid padding value */
if( padding_value < 1 || padding_value > modulus ){
return buffer_size;
}
/* buffer must be at least padding_value + 1 in size */
if( buffer_size < (unsigned long)padding_value + 1 ){
return 0;
}
uint8_t count = 1;
buffer_size --;
for( ; count < padding_value ; count++){
buffer_size --;
if( buffer[buffer_size] != padding_value ){
return 0;
}
}
return buffer_size;
}

View file

@ -0,0 +1,24 @@
#ifndef _PKCS7_PADDING_H_
#define _PKCS7_PADDING_H_
#include <stdint.h>
#include <stddef.h>
/* Pad a buffer with bytes as defined in PKCS#7
* Returns the number of pad bytes added, or zero if
* the buffer size is not large enough to hold the correctly padded data
*/
int pkcs7_padding_pad_buffer( uint8_t *buffer, size_t data_length, size_t buffer_size, uint8_t modulus );
int pkcs7_padding_valid( uint8_t *buffer, size_t data_length, size_t buffer_size, uint8_t modulus );
/* Given a block of pkcs7 padded data, return the actual data length in the block based on the padding applied.
* buffer_size must be a multiple of modulus
* last byte 'x' in buffer must be between 1 and modulus
* buffer_size must be at least x + 1 in size
* last 'x' bytes in buffer must be same as 'x'
* returned size will be buffer_size - 'x'
*/
size_t pkcs7_padding_data_length( uint8_t * buffer, size_t buffer_size, uint8_t modulus );
#endif

167
shared/thirdparty/tiny-AES128-C/sha1.C vendored Normal file
View file

@ -0,0 +1,167 @@
/* This code is public-domain - it is based on libcrypt
* placed in the public domain by Wei Dai and other contributors.
*/
#include "sha1.h"
#include <string.h>
#ifdef __BIG_ENDIAN__
# define SHA_BIG_ENDIAN
#elif defined __LITTLE_ENDIAN__
/* override */
#elif defined __BYTE_ORDER__
# if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
# define SHA_BIG_ENDIAN
# endif
#endif
#define SHA1_K0 0x5a827999
#define SHA1_K20 0x6ed9eba1
#define SHA1_K40 0x8f1bbcdc
#define SHA1_K60 0xca62c1d6
void sha1_init(sha1nfo *s) {
s->state[0] = 0x67452301;
s->state[1] = 0xefcdab89;
s->state[2] = 0x98badcfe;
s->state[3] = 0x10325476;
s->state[4] = 0xc3d2e1f0;
s->byteCount = 0;
s->bufferOffset = 0;
}
uint32_t sha1_rol32(uint32_t number, uint8_t bits) {
return ((number << bits) | (number >> (32-bits)));
}
void sha1_hashBlock(sha1nfo *s) {
uint8_t i;
uint32_t a,b,c,d,e,t;
a=s->state[0];
b=s->state[1];
c=s->state[2];
d=s->state[3];
e=s->state[4];
for (i=0; i<80; i++) {
if (i>=16) {
t = s->buffer[(i+13)&15] ^ s->buffer[(i+8)&15] ^ s->buffer[(i+2)&15] ^ s->buffer[i&15];
s->buffer[i&15] = sha1_rol32(t,1);
}
if (i<20) {
t = (d ^ (b & (c ^ d))) + SHA1_K0;
} else if (i<40) {
t = (b ^ c ^ d) + SHA1_K20;
} else if (i<60) {
t = ((b & c) | (d & (b | c))) + SHA1_K40;
} else {
t = (b ^ c ^ d) + SHA1_K60;
}
t+=sha1_rol32(a,5) + e + s->buffer[i&15];
e=d;
d=c;
c=sha1_rol32(b,30);
b=a;
a=t;
}
s->state[0] += a;
s->state[1] += b;
s->state[2] += c;
s->state[3] += d;
s->state[4] += e;
}
void sha1_addUncounted(sha1nfo *s, uint8_t data) {
uint8_t * const b = (uint8_t*) s->buffer;
#ifdef SHA_BIG_ENDIAN
b[s->bufferOffset] = data;
#else
b[s->bufferOffset ^ 3] = data;
#endif
s->bufferOffset++;
if (s->bufferOffset == BLOCK_LENGTH) {
sha1_hashBlock(s);
s->bufferOffset = 0;
}
}
void sha1_writebyte(sha1nfo *s, uint8_t data) {
++s->byteCount;
sha1_addUncounted(s, data);
}
void sha1_write(sha1nfo *s, const char *data, size_t len) {
for (;len--;) sha1_writebyte(s, (uint8_t) *data++);
}
void sha1_pad(sha1nfo *s) {
// Implement SHA-1 padding (fips180-2 §5.1.1)
// Pad with 0x80 followed by 0x00 until the end of the block
sha1_addUncounted(s, 0x80);
while (s->bufferOffset != 56) sha1_addUncounted(s, 0x00);
// Append length in the last 8 bytes
sha1_addUncounted(s, 0); // We're only using 32 bit lengths
sha1_addUncounted(s, 0); // But SHA-1 supports 64 bit lengths
sha1_addUncounted(s, 0); // So zero pad the top bits
sha1_addUncounted(s, s->byteCount >> 29); // Shifting to multiply by 8
sha1_addUncounted(s, s->byteCount >> 21); // as SHA-1 supports bitstreams as well as
sha1_addUncounted(s, s->byteCount >> 13); // byte.
sha1_addUncounted(s, s->byteCount >> 5);
sha1_addUncounted(s, s->byteCount << 3);
}
uint8_t* sha1_result(sha1nfo *s) {
// Pad to complete the last block
sha1_pad(s);
#ifndef SHA_BIG_ENDIAN
// Swap byte order back
int i;
for (i=0; i<5; i++) {
s->state[i]=
(((s->state[i])<<24)& 0xff000000)
| (((s->state[i])<<8) & 0x00ff0000)
| (((s->state[i])>>8) & 0x0000ff00)
| (((s->state[i])>>24)& 0x000000ff);
}
#endif
// Return pointer to hash (20 characters)
return (uint8_t*) s->state;
}
#define HMAC_IPAD 0x36
#define HMAC_OPAD 0x5c
void sha1_initHmac(sha1nfo *s, const uint8_t* key, int keyLength) {
uint8_t i;
memset(s->keyBuffer, 0, BLOCK_LENGTH);
if (keyLength > BLOCK_LENGTH) {
// Hash long keys
sha1_init(s);
for (;keyLength--;) sha1_writebyte(s, *key++);
memcpy(s->keyBuffer, sha1_result(s), HASH_LENGTH);
} else {
// Block length keys are used as is
memcpy(s->keyBuffer, key, keyLength);
}
// Start inner hash
sha1_init(s);
for (i=0; i<BLOCK_LENGTH; i++) {
sha1_writebyte(s, s->keyBuffer[i] ^ HMAC_IPAD);
}
}
uint8_t* sha1_resultHmac(sha1nfo *s) {
uint8_t i;
// Complete inner hash
memcpy(s->innerHash,sha1_result(s),HASH_LENGTH);
// Calculate outer hash
sha1_init(s);
for (i=0; i<BLOCK_LENGTH; i++) sha1_writebyte(s, s->keyBuffer[i] ^ HMAC_OPAD);
for (i=0; i<HASH_LENGTH; i++) sha1_writebyte(s, s->innerHash[i]);
return sha1_result(s);
}

45
shared/thirdparty/tiny-AES128-C/sha1.H vendored Normal file
View file

@ -0,0 +1,45 @@
#ifndef _SHA1_H_
#define _SHA1_H_
/* This code is public-domain - it is based on libcrypt
* placed in the public domain by Wei Dai and other contributors.
*/
// gcc -Wall -DSHA1TEST -o sha1test sha1.c && ./sha1test
#include <stdint.h>
#include <stddef.h>
#define HASH_LENGTH 20
#define BLOCK_LENGTH 64
typedef struct sha1nfo {
uint32_t buffer[BLOCK_LENGTH/4];
uint32_t state[HASH_LENGTH/4];
uint32_t byteCount;
uint8_t bufferOffset;
uint8_t keyBuffer[BLOCK_LENGTH];
uint8_t innerHash[HASH_LENGTH];
} sha1nfo;
/* public API - prototypes - TODO: doxygen*/
/**
*/
void sha1_init(sha1nfo *s);
/**
*/
void sha1_writebyte(sha1nfo *s, uint8_t data);
/**
*/
void sha1_write(sha1nfo *s, const char *data, size_t len);
/**
*/
uint8_t* sha1_result(sha1nfo *s);
/**
*/
void sha1_initHmac(sha1nfo *s, const uint8_t* key, int keyLength);
/**
*/
uint8_t* sha1_resultHmac(sha1nfo *s);
#endif

View file

@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>