--- /dev/null
+* Sergey Matveev <stargrave@stargrave.org>
--- /dev/null
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://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 <http://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
+<http://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
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
--- /dev/null
+No additional dependencies except Python 2.7/3.x interpreter are required.
+
+Preferable way is to download tarball with the signature from official
+website:
+
+ % wget http://www.cypherpunks.ru/pygost/pygost-2.1.tar.xz
+ % wget http://www.cypherpunks.ru/pygost/pygost-2.1.tar.xz.sig
+ % gpg --verify pygost-2.1.tar.xz.sig pygost-2.1.tar.xz
+ % xz -d < pygost-2.1.tar.xz | tar xf -
+ % cd pygost-2.1
+ % python setup.py install
+
+But also you can use PIP (NO authentication is performed!):
+
+ % pip install pygost==2.1
+
+You have to verify downloaded tarballs integrity and authenticity to be
+sure that you retrieved trusted and untampered software. GNU Privacy
+Guard is used for that purpose.
+
+For the very first time it it necessary to get signing public key and
+import it. It is provided below, but you should check alternative
+resources.
+
+ pub rsa2048/0xE6FD1269CD0C009E 2016-09-13
+ F55A 7619 3A0C 323A A031 0E6B E6FD 1269 CD0C 009E
+ uid PyGOST releases <pygost at cypherpunks dot ru>
+
+ Look in PUBKEY.asc file.
+ % gpg --keyserver hkp://keys.gnupg.net/ --recv-keys 0xE6FD1269CD0C009E
+ % gpg --auto-key-locate dane --locate-keys pygost at cypherpunks dot ru
+ % gpg --auto-key-locate wkd --locate-keys pygost at cypherpunks dot ru
+ % gpg --auto-key-locate pka --locate-keys pygost at cypherpunks dot ru
--- /dev/null
+2.3:
+ Typo and pylint fixes
+
+2.2:
+ 34.13-2015 padding methods
+
+2.1:
+ Documentation and supplementary files refactoring
+
+2.0:
+ PEP-0247 compatible hashers and MAC
+
+1.0:
+ * Ability to specify curve in pygost.x509 module
+ * Ability to use 34.10-2012 in pygost.x509 functions
+
+ Renamed classes and modules:
+
+ * pygost.gost3410.SIZE_34100 -> pygost.gost3410.SIZE_3410_2001
+ * pygost.gost3410.SIZE_34112 -> pygost.gost3410.SIZE_3410_2012
+ * pygost.gost3411_12.GOST341112 -> pygost.gost3411_2012.GOST34112012
+
+0.16:
+ 34.10-2012 TC26 curve parameters
+
+0.15:
+ PEP-0484 static typing hints
+
+0.14:
+ 34.10-2012 workability fix
+
+0.13:
+ Python3 compatibility
+
+0.11:
+ GOST R 34.12-2015 Кузнечик (Kuznechik) implementation
+
+0.10:
+ CryptoPro and GOST key wrapping, CryptoPro key meshing
--- /dev/null
+-----BEGIN PGP PUBLIC KEY BLOCK-----
+
+mQENBFfXoPQBCACfxmT1M/oDKh+3DxiIHwA2YdyJ0joxe+QhT1cACApvD9GBOlbS
+QqJU3kyO1+uOO5QzeTsSYdZbdcXF+Y7koEUsAVGY6aTKNKuuOrhVPTnhbG8Em++p
+i6LPAvHs1/pD9xYWgSyGueu5OrcUu1bk7Ii16BePkGdoVqIo53OrteNH8fabJ5Ga
+Rqvn2SxyTZ/HrgSfWqXOPmP62oiUKD6ztQPv1qP5GoSqPT3zXRF+c7yoJzAi09/D
+trKpOH+eZqj/5M1v853i/TIQE975+AH9HNuIK3XYt67VQiDqU3CFeWC6wFUt/FOD
+eAA9pKuJvY7eCyKVCOuNYJ5af1fGuxrEZPxJABEBAAG0J1B5R09TVCByZWxlYXNl
+cyA8cHlnb3N0QGN5cGhlcnB1bmtzLnJ1PokBQAQTAQgAKgUCV9eg9AIbAwwLCgkN
+CAwHCwMEAQIHFQoJCAsDAgUWAgEDAAIeAQIXgAAKCRDm/RJpzQwAnkiQB/wLD29x
+75urRIOCxLKrynERF2z/lxUv8aA6VB6Bp3/c08xbrtrNKpq970WvcxyNrsTFgcno
+Sc2QBwGjSM4Oh5z1UxHt8wLvk+FTOYxlkUiOQv9uCwhU4ZtypV7Ps759dwneY2nS
+Y0R5oGa3nFhi7JujBu7/9Xr2riBBczsGh3chFUe/WeQZxwfF4ZJFN/ykJpvlwkhe
+txhAWSG2JTR9xDxbt6JBzdZ8hmS9YNZrzzyU3XUkdATi6zgkgv8BYPlc/QUCBVYp
+xukpfqopwuT0QPKXZjPEBUNRAXGtPMo83OQyanMLm/BkSJXFBO2mVjaalEohc7Iq
+jMcy/DjqMIpsOdVfiF4EEBEIAAYFAlfXoRkACgkQrhqBCeSYV+9zEgD/Weliq0bC
+bQbT+AV0oPSsh4cl7/7yBWXuERUm0uIsDRsA/RSss+81tbyKTt8oObmDqi3gt8ka
+6j2AvJWj4I8J/fT9
+=pQ8y
+-----END PGP PUBLIC KEY BLOCK-----
--- /dev/null
+Pure Python 2.7/3.x GOST cryptographic functions library.
+
+GOST is GOvernment STandard of Russian Federation (and Soviet Union).
+
+* GOST 28147-89 (RFC 5830) block cipher with ECB, CNT (CTR), CFB, MAC,
+ CBC (RFC 4357) modes of operation
+* various 28147-89-related S-boxes included
+* GOST R 34.11-94 hash function (RFC 5831)
+* GOST R 34.11-2012 Стрибог (Streebog) hash function (RFC 6986)
+* GOST R 34.10-2001 (RFC 5832) public key signature function
+* GOST R 34.10-2012 (RFC 7091) public key signature function
+* various 34.10 curve parameters included
+* VKO 34.10-2001 Diffie-Hellman function (RFC 4357)
+* 28147-89 and CryptoPro key wrapping (RFC 4357)
+* 28147-89 CryptoPro key meshing for CFB mode (RFC 4357)
+* RFC 4491 (using GOST algorithms with X.509) compatibility helpers
+* GOST R 34.12-2015 128-bit block cipher Кузнечик (Kuznechik) (RFC 7801)
+* GOST R 34.13-2015 padding methods
+* PEP247-compatible hash/MAC functions
+
+Known problems: low performance and non time-constant calculations.
+
+Example X.509 compatible 34.10-2012 keypair generation, signing and
+verifying its signature:
+
+ >>> from pygost import x509
+ >>> prv, pub = x509.keypair_gen(urandom(64), mode=2012)
+ >>> data = b'some data'
+ >>> signature = x509.sign(prv, data, mode=2012)
+ >>> x509.verify(pub, data, signature, mode=2012)
+ True
+
+Other examples can be found in docstrings.
+
+PyGOST is free software: see the file COPYING for copying conditions.
+
+PyGOST'es home page is: http://www.cypherpunks.ru/pygost/
+
+Please send questions, bug reports and patches to
+https://lists.cypherpunks.ru/mailman/listinfo/gost
+mailing list. Announcements also go to this mailing list.
+
+Development Git source code repository currently is located here:
+http://git.cypherpunks.ru/cgit.cgi/pygost.git/
--- /dev/null
+#!/bin/sh -ex
+
+cur=$(pwd)
+tmp=$(mktemp -d)
+release=$1
+[ -n "$release" ]
+
+cp dist/pygost-"$release".tar.gz $tmp
+cd $tmp
+gunzip pygost-"$release".tar.gz
+xz -9 pygost-"$release".tar
+gpg --detach-sign --sign --local-user E6FD1269CD0C009E pygost-"$release".tar.xz
+
+tarball=pygost-"$release".tar.xz
+size=$(( $(wc -c < $tarball) / 1024 ))
+hash=$(gpg --print-md SHA256 < $tarball)
+hashsb=$($HOME/work/gogost/gogost-streebog < $tarball)
+
+cat <<EOF
+An entry for documentation:
+@item $release @tab $size KiB
+@tab @url{pygost-${release}.tar.xz, link} @url{pygost-${release}.tar.xz.sig, sign}
+@tab @code{$hash}
+@tab @code{$hashsb}
+EOF
+
+cat <<EOF
+Subject: PyGOST $release release announcement
+
+I am pleased to announce PyGOST $release release availability!
+
+PyGOST is free software pure Python GOST cryptographic functions library.
+GOST is GOvernment STandard of Russian Federation (and Soviet Union).
+
+------------------------ >8 ------------------------
+
+The main improvements for that release are:
+
+
+------------------------ >8 ------------------------
+
+PyGOST'es home page is: http://www.cypherpunks.ru/pygost/
+
+Source code and its signature for that version can be found here:
+
+ http://www.cypherpunks.ru/pygost/pygost-${release}.tar.xz ($size KiB)
+ http://www.cypherpunks.ru/pygost/pygost-${release}.tar.xz.sig
+
+Streebog-256 hash: $hashsb
+SHA256 hash: $hash
+GPG key ID: 0xE6FD1269CD0C009E PyGOST releases <pygost at cypherpunks dot ru>
+Fingerprint: F55A 7619 3A0C 323A A031 0E6B E6FD 1269 CD0C 009E
+
+Please send questions regarding the use of PyGOST, bug reports and patches
+to mailing list: https://lists.cypherpunks.ru/mailman/listinfo/gost
+EOF
+
+mv $tmp/$tarball $tmp/"$tarball".sig $cur/pygost.html/
--- /dev/null
+PYTHON ?= python
+
+test:
+ PYTHONPATH=.. $(PYTHON) -m unittest test_gost28147
+ PYTHONPATH=.. $(PYTHON) -m unittest test_gost28147_mac
+ PYTHONPATH=.. $(PYTHON) -m unittest test_gost3411_94
+ PYTHONPATH=.. $(PYTHON) -m unittest test_gost3411_2012
+ PYTHONPATH=.. $(PYTHON) -m unittest test_gost3410
+ PYTHONPATH=.. $(PYTHON) -m unittest test_x509
+ PYTHONPATH=.. $(PYTHON) -m unittest test_wrap
+ PYTHONPATH=.. $(PYTHON) -m unittest test_gost3412
--- /dev/null
+""" Pure Python GOST cryptographic functions library.
+
+PyGOST is free software: see the file COPYING for copying conditions.
+"""
--- /dev/null
+# coding: utf-8
+# PyGOST -- Pure Python GOST cryptographic functions library
+# Copyright (C) 2015-2016 Sergey Matveev <stargrave@stargrave.org>
+#
+# 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 <http://www.gnu.org/licenses/>.
+""" GOST 28147-89 block cipher
+
+This is implementation of :rfc:`5830` ECB, CNT, CFB and :rfc:`4357`
+CBC modes of operation. N1, N2, K names are taken according to
+specification's terminology. CNT and CFB modes can work with arbitrary
+data lengths.
+"""
+
+from functools import partial
+
+from pygost.gost3413 import pad1
+from pygost.gost3413 import pad2
+from pygost.utils import hexdec
+from pygost.utils import strxor
+from pygost.utils import xrange
+
+
+KEYSIZE = 32
+BLOCKSIZE = 8
+C1 = 0x01010104
+C2 = 0x01010101
+
+# Sequence of K_i S-box applying for encryption and decryption
+SEQ_ENCRYPT = (
+ 0, 1, 2, 3, 4, 5, 6, 7,
+ 0, 1, 2, 3, 4, 5, 6, 7,
+ 0, 1, 2, 3, 4, 5, 6, 7,
+ 7, 6, 5, 4, 3, 2, 1, 0,
+)
+SEQ_DECRYPT = (
+ 0, 1, 2, 3, 4, 5, 6, 7,
+ 7, 6, 5, 4, 3, 2, 1, 0,
+ 7, 6, 5, 4, 3, 2, 1, 0,
+ 7, 6, 5, 4, 3, 2, 1, 0,
+)
+
+# S-box parameters
+DEFAULT_SBOX = "Gost28147_CryptoProParamSetA"
+SBOXES = {
+ "Gost2814789_TestParamSet": (
+ (4, 2, 15, 5, 9, 1, 0, 8, 14, 3, 11, 12, 13, 7, 10, 6),
+ (12, 9, 15, 14, 8, 1, 3, 10, 2, 7, 4, 13, 6, 0, 11, 5),
+ (13, 8, 14, 12, 7, 3, 9, 10, 1, 5, 2, 4, 6, 15, 0, 11),
+ (14, 9, 11, 2, 5, 15, 7, 1, 0, 13, 12, 6, 10, 4, 3, 8),
+ (3, 14, 5, 9, 6, 8, 0, 13, 10, 11, 7, 12, 2, 1, 15, 4),
+ (8, 15, 6, 11, 1, 9, 12, 5, 13, 3, 7, 10, 0, 14, 2, 4),
+ (9, 11, 12, 0, 3, 6, 7, 5, 4, 8, 14, 15, 1, 10, 2, 13),
+ (12, 6, 5, 2, 11, 0, 9, 13, 3, 14, 7, 10, 15, 4, 1, 8),
+ ),
+ "Gost28147_CryptoProParamSetA": (
+ (9, 6, 3, 2, 8, 11, 1, 7, 10, 4, 14, 15, 12, 0, 13, 5),
+ (3, 7, 14, 9, 8, 10, 15, 0, 5, 2, 6, 12, 11, 4, 13, 1),
+ (14, 4, 6, 2, 11, 3, 13, 8, 12, 15, 5, 10, 0, 7, 1, 9),
+ (14, 7, 10, 12, 13, 1, 3, 9, 0, 2, 11, 4, 15, 8, 5, 6),
+ (11, 5, 1, 9, 8, 13, 15, 0, 14, 4, 2, 3, 12, 7, 10, 6),
+ (3, 10, 13, 12, 1, 2, 0, 11, 7, 5, 9, 4, 8, 15, 14, 6),
+ (1, 13, 2, 9, 7, 10, 6, 0, 8, 12, 4, 5, 15, 3, 11, 14),
+ (11, 10, 15, 5, 0, 12, 14, 8, 6, 2, 3, 9, 1, 7, 13, 4),
+ ),
+ "Gost28147_CryptoProParamSetB": (
+ (8, 4, 11, 1, 3, 5, 0, 9, 2, 14, 10, 12, 13, 6, 7, 15),
+ (0, 1, 2, 10, 4, 13, 5, 12, 9, 7, 3, 15, 11, 8, 6, 14),
+ (14, 12, 0, 10, 9, 2, 13, 11, 7, 5, 8, 15, 3, 6, 1, 4),
+ (7, 5, 0, 13, 11, 6, 1, 2, 3, 10, 12, 15, 4, 14, 9, 8),
+ (2, 7, 12, 15, 9, 5, 10, 11, 1, 4, 0, 13, 6, 8, 14, 3),
+ (8, 3, 2, 6, 4, 13, 14, 11, 12, 1, 7, 15, 10, 0, 9, 5),
+ (5, 2, 10, 11, 9, 1, 12, 3, 7, 4, 13, 0, 6, 15, 8, 14),
+ (0, 4, 11, 14, 8, 3, 7, 1, 10, 2, 9, 6, 15, 13, 5, 12),
+ ),
+ "Gost28147_CryptoProParamSetC": (
+ (1, 11, 12, 2, 9, 13, 0, 15, 4, 5, 8, 14, 10, 7, 6, 3),
+ (0, 1, 7, 13, 11, 4, 5, 2, 8, 14, 15, 12, 9, 10, 6, 3),
+ (8, 2, 5, 0, 4, 9, 15, 10, 3, 7, 12, 13, 6, 14, 1, 11),
+ (3, 6, 0, 1, 5, 13, 10, 8, 11, 2, 9, 7, 14, 15, 12, 4),
+ (8, 13, 11, 0, 4, 5, 1, 2, 9, 3, 12, 14, 6, 15, 10, 7),
+ (12, 9, 11, 1, 8, 14, 2, 4, 7, 3, 6, 5, 10, 0, 15, 13),
+ (10, 9, 6, 8, 13, 14, 2, 0, 15, 3, 5, 11, 4, 1, 12, 7),
+ (7, 4, 0, 5, 10, 2, 15, 14, 12, 6, 1, 11, 13, 9, 3, 8),
+ ),
+ "Gost28147_CryptoProParamSetD": (
+ (15, 12, 2, 10, 6, 4, 5, 0, 7, 9, 14, 13, 1, 11, 8, 3),
+ (11, 6, 3, 4, 12, 15, 14, 2, 7, 13, 8, 0, 5, 10, 9, 1),
+ (1, 12, 11, 0, 15, 14, 6, 5, 10, 13, 4, 8, 9, 3, 7, 2),
+ (1, 5, 14, 12, 10, 7, 0, 13, 6, 2, 11, 4, 9, 3, 15, 8),
+ (0, 12, 8, 9, 13, 2, 10, 11, 7, 3, 6, 5, 4, 14, 15, 1),
+ (8, 0, 15, 3, 2, 5, 14, 11, 1, 10, 4, 7, 12, 9, 13, 6),
+ (3, 0, 6, 15, 1, 14, 9, 2, 13, 8, 12, 4, 11, 10, 5, 7),
+ (1, 10, 6, 8, 15, 11, 0, 4, 12, 3, 5, 9, 7, 13, 2, 14),
+ ),
+ "GostR3411_94_TestParamSet": (
+ (4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3),
+ (14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9),
+ (5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11),
+ (7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3),
+ (6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2),
+ (4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14),
+ (13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12),
+ (1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12),
+ ),
+ "GostR3411_94_CryptoProParamSet": (
+ (10, 4, 5, 6, 8, 1, 3, 7, 13, 12, 14, 0, 9, 2, 11, 15),
+ (5, 15, 4, 0, 2, 13, 11, 9, 1, 7, 6, 3, 12, 14, 10, 8),
+ (7, 15, 12, 14, 9, 4, 1, 0, 3, 11, 5, 2, 6, 10, 8, 13),
+ (4, 10, 7, 12, 0, 15, 2, 8, 14, 1, 6, 5, 13, 11, 9, 3),
+ (7, 6, 4, 11, 9, 12, 2, 10, 1, 8, 0, 14, 15, 13, 3, 5),
+ (7, 6, 2, 4, 13, 9, 15, 0, 10, 1, 5, 11, 8, 14, 12, 3),
+ (13, 14, 4, 1, 7, 0, 5, 10, 3, 12, 8, 15, 6, 2, 9, 11),
+ (1, 3, 10, 9, 5, 11, 4, 15, 8, 6, 7, 14, 13, 0, 2, 12),
+ ),
+ "AppliedCryptography": (
+ (4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3),
+ (14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9),
+ (5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11),
+ (7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3),
+ (6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2),
+ (4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14),
+ (13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12),
+ (1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12),
+ ),
+ "Gost28147_tc26_ParamZ": (
+ (12, 4, 6, 2, 10, 5, 11, 9, 14, 8, 13, 7, 0, 3, 15, 1),
+ (6, 8, 2, 3, 9, 10, 5, 12, 1, 14, 4, 7, 11, 13, 0, 15),
+ (11, 3, 5, 8, 2, 15, 10, 13, 14, 1, 7, 4, 12, 9, 6, 0),
+ (12, 8, 2, 1, 13, 4, 15, 6, 7, 0, 10, 5, 3, 14, 9, 11),
+ (7, 15, 5, 10, 8, 1, 6, 13, 0, 9, 3, 14, 11, 4, 2, 12),
+ (5, 13, 15, 6, 9, 2, 12, 10, 11, 7, 8, 1, 4, 3, 14, 0),
+ (8, 14, 2, 5, 6, 9, 1, 12, 15, 4, 11, 0, 13, 10, 3, 7),
+ (1, 7, 14, 13, 0, 5, 8, 3, 4, 15, 10, 6, 9, 12, 11, 2),
+ ),
+ "EACParamSet": (
+ (11, 4, 8, 10, 9, 7, 0, 3, 1, 6, 2, 15, 14, 5, 12, 13),
+ (1, 7, 14, 9, 11, 3, 15, 12, 0, 5, 4, 6, 13, 10, 8, 2),
+ (7, 3, 1, 9, 2, 4, 13, 15, 8, 10, 12, 6, 5, 0, 11, 14),
+ (10, 5, 15, 7, 14, 11, 3, 9, 2, 8, 1, 12, 0, 4, 6, 13),
+ (0, 14, 6, 11, 9, 3, 8, 4, 12, 15, 10, 5, 13, 7, 1, 2),
+ (9, 2, 11, 12, 0, 4, 5, 6, 3, 15, 13, 8, 1, 7, 14, 10),
+ (4, 0, 14, 1, 5, 11, 8, 3, 12, 2, 9, 7, 6, 10, 13, 15),
+ (7, 14, 12, 13, 9, 4, 8, 15, 10, 2, 6, 0, 3, 11, 5, 1),
+ ),
+}
+
+
+def _K(s, _in):
+ """ S-box substitution
+
+ :param s: S-box
+ :param _in: 32-bit word
+ :return: substituted 32-bit word
+ """
+ return (
+ (s[0][(_in >> 0) & 0x0F] << 0) +
+ (s[1][(_in >> 4) & 0x0F] << 4) +
+ (s[2][(_in >> 8) & 0x0F] << 8) +
+ (s[3][(_in >> 12) & 0x0F] << 12) +
+ (s[4][(_in >> 16) & 0x0F] << 16) +
+ (s[5][(_in >> 20) & 0x0F] << 20) +
+ (s[6][(_in >> 24) & 0x0F] << 24) +
+ (s[7][(_in >> 28) & 0x0F] << 28)
+ )
+
+
+def block2ns(data):
+ """ Convert block to N1 and N2 integers
+ """
+ data = bytearray(data)
+ return (
+ data[0] | data[1] << 8 | data[2] << 16 | data[3] << 24,
+ data[4] | data[5] << 8 | data[6] << 16 | data[7] << 24,
+ )
+
+
+def ns2block(ns):
+ """ Convert N1 and N2 integers to 8-byte block
+ """
+ n1, n2 = ns
+ return bytes(bytearray((
+ (n2 >> 0) & 255, (n2 >> 8) & 255, (n2 >> 16) & 255, (n2 >> 24) & 255,
+ (n1 >> 0) & 255, (n1 >> 8) & 255, (n1 >> 16) & 255, (n1 >> 24) & 255,
+ )))
+
+
+def addmod(x, y, mod=2 ** 32):
+ """ Modulo adding of two integers
+ """
+ r = x + y
+ return r if r < mod else r - mod
+
+
+def _shift11(x):
+ """ 11-bit cyclic shift
+ """
+ return ((x << 11) & (2 ** 32 - 1)) | ((x >> (32 - 11)) & (2 ** 32 - 1))
+
+
+def validate_key(key):
+ if len(key) != KEYSIZE:
+ raise ValueError("Invalid key size")
+
+
+def validate_iv(iv):
+ if len(iv) != BLOCKSIZE:
+ raise ValueError("Invalid IV size")
+
+
+def validate_sbox(sbox):
+ if sbox not in SBOXES:
+ raise ValueError("Unknown sbox supplied")
+
+
+def xcrypt(seq, sbox, key, ns):
+ """ Perform full-round single-block operation
+
+ :param seq: sequence of K_i S-box applying (either encrypt or decrypt)
+ :param sbox: S-box parameters to use
+ :type sbox: str, SBOXES'es key
+ :param bytes key: 256-bit encryption key
+ :param ns: N1 and N2 integers
+ :type ns: (int, int)
+ :return: resulting N1 and N2
+ :rtype: (int, int)
+ """
+ s = SBOXES[sbox]
+ w = bytearray(key)
+ x = [
+ w[0 + i * 4] |
+ w[1 + i * 4] << 8 |
+ w[2 + i * 4] << 16 |
+ w[3 + i * 4] << 24 for i in range(8)
+ ]
+ n1, n2 = ns
+ for i in seq:
+ n1, n2 = _shift11(_K(s, addmod(n1, x[i]))) ^ n2, n1
+ return n1, n2
+
+
+def encrypt(sbox, key, ns):
+ """ Encrypt single block
+ """
+ return xcrypt(SEQ_ENCRYPT, sbox, key, ns)
+
+
+def decrypt(sbox, key, ns):
+ """ Decrypt single block
+ """
+ return xcrypt(SEQ_DECRYPT, sbox, key, ns)
+
+
+def ecb(key, data, action, sbox=DEFAULT_SBOX):
+ """ ECB mode of operation
+
+ :param bytes key: encryption key
+ :param data: plaintext
+ :type data: bytes, multiple of BLOCKSIZE
+ :param func action: encrypt/decrypt
+ :param sbox: S-box parameters to use
+ :type sbox: str, SBOXES'es key
+ :return: ciphertext
+ :rtype: bytes
+ """
+ validate_key(key)
+ validate_sbox(sbox)
+ if not data or len(data) % BLOCKSIZE != 0:
+ raise ValueError("Data is not blocksize aligned")
+ result = []
+ for i in xrange(0, len(data), BLOCKSIZE):
+ result.append(ns2block(action(
+ sbox, key, block2ns(data[i:i + BLOCKSIZE])
+ )))
+ return b''.join(result)
+
+
+ecb_encrypt = partial(ecb, action=encrypt)
+ecb_decrypt = partial(ecb, action=decrypt)
+
+
+def cbc_encrypt(key, data, iv=8 * b'\x00', pad=True, sbox=DEFAULT_SBOX):
+ """ CBC encryption mode of operation
+
+ :param bytes key: encryption key
+ :param bytes data: plaintext
+ :param iv: initialization vector
+ :type iv: bytes, BLOCKSIZE length
+ :type bool pad: perform ISO/IEC 7816-4 padding
+ :param sbox: S-box parameters to use
+ :type sbox: str, SBOXES'es key
+ :return: ciphertext
+ :rtype: bytes
+
+ 34.13-2015 padding method 2 is used.
+ """
+ validate_key(key)
+ validate_iv(iv)
+ validate_sbox(sbox)
+ if not data:
+ raise ValueError("No data supplied")
+ if pad:
+ data = pad2(data, BLOCKSIZE)
+ if len(data) % BLOCKSIZE != 0:
+ raise ValueError("Data is not blocksize aligned")
+ ciphertext = [iv]
+ for i in xrange(0, len(data), BLOCKSIZE):
+ ciphertext.append(ns2block(encrypt(sbox, key, block2ns(
+ strxor(ciphertext[-1], data[i:i + BLOCKSIZE])
+ ))))
+ return b''.join(ciphertext)
+
+
+def cbc_decrypt(key, data, pad=True, sbox=DEFAULT_SBOX):
+ """ CBC decryption mode of operation
+
+ :param bytes key: encryption key
+ :param bytes data: ciphertext
+ :param iv: initialization vector
+ :type iv: bytes, BLOCKSIZE length
+ :type bool pad: perform ISO/IEC 7816-4 unpadding after decryption
+ :param sbox: S-box parameters to use
+ :type sbox: str, SBOXES'es key
+ :return: plaintext
+ :rtype: bytes
+ """
+ validate_key(key)
+ validate_sbox(sbox)
+ if not data or len(data) % BLOCKSIZE != 0:
+ raise ValueError("Data is not blocksize aligned")
+ if len(data) < 2 * BLOCKSIZE:
+ raise ValueError("There is no either data, or IV in ciphertext")
+ plaintext = []
+ for i in xrange(BLOCKSIZE, len(data), BLOCKSIZE):
+ plaintext.append(strxor(
+ ns2block(decrypt(sbox, key, block2ns(data[i:i + BLOCKSIZE]))),
+ data[i - BLOCKSIZE:i],
+ ))
+ if pad:
+ last_block = bytearray(plaintext[-1])
+ pad_index = last_block.rfind(b'\x80')
+ if pad_index == -1:
+ raise ValueError("Invalid padding")
+ for c in last_block[pad_index + 1:]:
+ if c != 0:
+ raise ValueError("Invalid padding")
+ plaintext[-1] = bytes(last_block[:pad_index])
+ return b''.join(plaintext)
+
+
+def cnt(key, data, iv=8 * b'\x00', sbox=DEFAULT_SBOX):
+ """ Counter mode of operation
+
+ :param bytes key: encryption key
+ :param bytes data: plaintext
+ :param iv: initialization vector
+ :type iv: bytes, BLOCKSIZE length
+ :param sbox: S-box parameters to use
+ :type sbox: str, SBOXES'es key
+ :return: ciphertext
+ :rtype: bytes
+
+ For decryption you use the same function again.
+ """
+ validate_key(key)
+ validate_iv(iv)
+ validate_sbox(sbox)
+ if not data:
+ raise ValueError("No data supplied")
+ n2, n1 = encrypt(sbox, key, block2ns(iv))
+ size = len(data)
+ data = pad1(data, BLOCKSIZE)
+ gamma = []
+ for _ in xrange(0, len(data), BLOCKSIZE):
+ n1 = addmod(n1, C2, 2 ** 32)
+ n2 = addmod(n2, C1, 2 ** 32 - 1)
+ gamma.append(ns2block(encrypt(sbox, key, (n1, n2))))
+ return strxor(b''.join(gamma), data[:size])
+
+
+MESH_CONST = hexdec("6900722264C904238D3ADB9646E92AC418FEAC9400ED0712C086DCC2EF4CA92B")
+MESH_MAX_DATA = 1024
+
+
+def meshing(key, iv, sbox=DEFAULT_SBOX):
+ """:rfc:`4357` key meshing
+ """
+ key = ecb_decrypt(key, MESH_CONST, sbox=sbox)
+ iv = ecb_encrypt(key, iv, sbox=sbox)
+ return key, iv
+
+
+def cfb_encrypt(key, data, iv=8 * b'\x00', sbox=DEFAULT_SBOX, mesh=False):
+ """ CFB encryption mode of operation
+
+ :param bytes key: encryption key
+ :param bytes data: plaintext
+ :param iv: initialization vector
+ :type iv: bytes, BLOCKSIZE length
+ :param sbox: S-box parameters to use
+ :type sbox: str, SBOXES'es key
+ :param bool mesh: enable key meshing
+ :return: ciphertext
+ :rtype: bytes
+ """
+ validate_key(key)
+ validate_iv(iv)
+ validate_sbox(sbox)
+ if not data:
+ raise ValueError("No data supplied")
+ size = len(data)
+ data = pad1(data, BLOCKSIZE)
+ ciphertext = [iv]
+ for i in xrange(0, len(data), BLOCKSIZE):
+ if mesh and i >= MESH_MAX_DATA and i % MESH_MAX_DATA == 0:
+ key, iv = meshing(key, ciphertext[-1], sbox=sbox)
+ ciphertext.append(strxor(
+ data[i:i + BLOCKSIZE],
+ ns2block(encrypt(sbox, key, block2ns(iv))),
+ ))
+ continue
+ ciphertext.append(strxor(
+ data[i:i + BLOCKSIZE],
+ ns2block(encrypt(sbox, key, block2ns(ciphertext[-1]))),
+ ))
+ return b''.join(ciphertext[1:])[:size]
+
+
+def cfb_decrypt(key, data, iv=8 * b'\x00', sbox=DEFAULT_SBOX, mesh=False):
+ """ CFB decryption mode of operation
+
+ :param bytes key: encryption key
+ :param bytes data: plaintext
+ :param iv: initialization vector
+ :type iv: bytes, BLOCKSIZE length
+ :param sbox: S-box parameters to use
+ :type sbox: str, SBOXES'es key
+ :param bool mesh: enable key meshing
+ :return: ciphertext
+ :rtype: bytes
+ """
+ validate_key(key)
+ validate_iv(iv)
+ validate_sbox(sbox)
+ if not data:
+ raise ValueError("No data supplied")
+ size = len(data)
+ data = pad1(data, BLOCKSIZE)
+ plaintext = []
+ data = iv + data
+ for i in xrange(BLOCKSIZE, len(data), BLOCKSIZE):
+ if (
+ mesh and
+ (i - BLOCKSIZE) >= MESH_MAX_DATA and
+ (i - BLOCKSIZE) % MESH_MAX_DATA == 0
+ ):
+ key, iv = meshing(key, data[i - BLOCKSIZE:i], sbox=sbox)
+ plaintext.append(strxor(
+ data[i:i + BLOCKSIZE],
+ ns2block(encrypt(sbox, key, block2ns(iv))),
+ ))
+ continue
+ plaintext.append(strxor(
+ data[i:i + BLOCKSIZE],
+ ns2block(encrypt(sbox, key, block2ns(data[i - BLOCKSIZE:i]))),
+ ))
+ return b''.join(plaintext)[:size]
--- /dev/null
+# coding: utf-8
+# PyGOST -- Pure Python GOST cryptographic functions library
+# Copyright (C) 2015-2016 Sergey Matveev <stargrave@stargrave.org>
+#
+# 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 <http://www.gnu.org/licenses/>.
+""" GOST 28147-89 MAC
+"""
+
+from copy import copy
+
+from pygost.gost28147 import block2ns
+from pygost.gost28147 import BLOCKSIZE
+from pygost.gost28147 import DEFAULT_SBOX
+from pygost.gost28147 import ns2block
+from pygost.gost28147 import validate_iv
+from pygost.gost28147 import validate_key
+from pygost.gost28147 import validate_sbox
+from pygost.gost28147 import xcrypt
+from pygost.gost3413 import pad1
+from pygost.iface import PEP247
+from pygost.utils import hexenc
+from pygost.utils import strxor
+from pygost.utils import xrange
+
+digest_size = 8
+SEQ_MAC = (
+ 0, 1, 2, 3, 4, 5, 6, 7,
+ 0, 1, 2, 3, 4, 5, 6, 7,
+)
+
+
+class MAC(PEP247):
+ """ GOST 28147-89 MAC mode of operation
+
+ >>> m = MAC(key=key)
+ >>> m.update("some data")
+ >>> m.update("another data")
+ >>> m.hexdigest()[:8]
+ 'a687a08b'
+ """
+ digest_size = digest_size
+
+ def __init__(self, key, data=b'', iv=8 * b'\x00', sbox=DEFAULT_SBOX):
+ """
+ :param key: authentication key
+ :type key: bytes, 32 bytes
+ :param iv: initialization vector
+ :type iv: bytes, BLOCKSIZE length
+ :param sbox: S-box parameters to use
+ :type sbox: str, SBOXES'es key
+ """
+ validate_key(key)
+ validate_iv(iv)
+ validate_sbox(sbox)
+ self.key = key
+ self.data = data
+ self.iv = iv
+ self.sbox = sbox
+
+ def copy(self):
+ return MAC(self.key, copy(self.data), self.iv, self.sbox)
+
+ def update(self, data):
+ """ Append data that has to be authenticated
+ """
+ self.data += data
+
+ def digest(self):
+ """ Get MAC tag of supplied data
+
+ You have to provide at least single byte of data.
+ If you want to produce tag length of 3 bytes, then
+ ``digest()[:3]``.
+ """
+ if not self.data:
+ raise ValueError("No data processed")
+ data = pad1(self.data, BLOCKSIZE)
+ prev = block2ns(self.iv)[::-1]
+ for i in xrange(0, len(data), BLOCKSIZE):
+ prev = xcrypt(
+ SEQ_MAC, self.sbox, self.key, block2ns(strxor(
+ data[i:i + BLOCKSIZE],
+ ns2block(prev),
+ )),
+ )[::-1]
+ return ns2block(prev)
+
+ def hexdigest(self):
+ return hexenc(self.digest())
+
+
+def new(key, data=b'', iv=8 * b'\x00', sbox=DEFAULT_SBOX):
+ return MAC(key, data, iv, sbox)
--- /dev/null
+# coding: utf-8
+# PyGOST -- Pure Python GOST cryptographic functions library
+# Copyright (C) 2015-2016 Sergey Matveev <stargrave@stargrave.org>
+#
+# 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 <http://www.gnu.org/licenses/>.
+""" GOST R 34.10 public-key signature function.
+
+This is implementation of GOST R 34.10-2001 (:rfc:`5832`), GOST R
+34.10-2012 (:rfc:`7091`). The difference between 2001 and 2012 is the
+key, digest and signature lengths.
+"""
+
+from os import urandom
+
+from pygost.gost3411_94 import GOST341194
+from pygost.utils import bytes2long
+from pygost.utils import hexdec
+from pygost.utils import long2bytes
+from pygost.utils import modinvert
+
+
+SIZE_3410_2001 = 32
+SIZE_3410_2012 = 64
+
+
+DEFAULT_CURVE = "GostR3410_2001_CryptoPro_A_ParamSet"
+# Curve parameters are the following: p, q, a, b, x, y
+CURVE_PARAMS = {
+ "GostR3410_2001_ParamSet_cc": (
+ "C0000000000000000000000000000000000000000000000000000000000003C7",
+ "5fffffffffffffffffffffffffffffff606117a2f4bde428b7458a54b6e87b85",
+ "C0000000000000000000000000000000000000000000000000000000000003c4",
+ "2d06B4265ebc749ff7d0f1f1f88232e81632e9088fd44b7787d5e407e955080c",
+ "0000000000000000000000000000000000000000000000000000000000000002",
+ "a20e034bf8813ef5c18d01105e726a17eb248b264ae9706f440bedc8ccb6b22c",
+ ),
+ "GostR3410_2001_TestParamSet": (
+ "8000000000000000000000000000000000000000000000000000000000000431",
+ "8000000000000000000000000000000150FE8A1892976154C59CFC193ACCF5B3",
+ "0000000000000000000000000000000000000000000000000000000000000007",
+ "5FBFF498AA938CE739B8E022FBAFEF40563F6E6A3472FC2A514C0CE9DAE23B7E",
+ "0000000000000000000000000000000000000000000000000000000000000002",
+ "08E2A8A0E65147D4BD6316030E16D19C85C97F0A9CA267122B96ABBCEA7E8FC8",
+ ),
+ "GostR3410_2001_CryptoPro_A_ParamSet": (
+ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD97",
+ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF6C611070995AD10045841B09B761B893",
+ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD94",
+ "00000000000000000000000000000000000000000000000000000000000000a6",
+ "0000000000000000000000000000000000000000000000000000000000000001",
+ "8D91E471E0989CDA27DF505A453F2B7635294F2DDF23E3B122ACC99C9E9F1E14",
+ ),
+ "GostR3410_2001_CryptoPro_B_ParamSet": (
+ "8000000000000000000000000000000000000000000000000000000000000C99",
+ "800000000000000000000000000000015F700CFFF1A624E5E497161BCC8A198F",
+ "8000000000000000000000000000000000000000000000000000000000000C96",
+ "3E1AF419A269A5F866A7D3C25C3DF80AE979259373FF2B182F49D4CE7E1BBC8B",
+ "0000000000000000000000000000000000000000000000000000000000000001",
+ "3FA8124359F96680B83D1C3EB2C070E5C545C9858D03ECFB744BF8D717717EFC",
+ ),
+ "GostR3410_2001_CryptoPro_C_ParamSet": (
+ "9B9F605F5A858107AB1EC85E6B41C8AACF846E86789051D37998F7B9022D759B",
+ "9B9F605F5A858107AB1EC85E6B41C8AA582CA3511EDDFB74F02F3A6598980BB9",
+ "9B9F605F5A858107AB1EC85E6B41C8AACF846E86789051D37998F7B9022D7598",
+ "000000000000000000000000000000000000000000000000000000000000805a",
+ "0000000000000000000000000000000000000000000000000000000000000000",
+ "41ECE55743711A8C3CBF3783CD08C0EE4D4DC440D4641A8F366E550DFDB3BB67",
+ ),
+ "GostR3410_2001_CryptoPro_XchA_ParamSet": (
+ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD97",
+ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF6C611070995AD10045841B09B761B893",
+ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD94",
+ "00000000000000000000000000000000000000000000000000000000000000a6",
+ "0000000000000000000000000000000000000000000000000000000000000001",
+ "8D91E471E0989CDA27DF505A453F2B7635294F2DDF23E3B122ACC99C9E9F1E14",
+ ),
+ "GostR3410_2001_CryptoPro_XchB_ParamSet": (
+ "9B9F605F5A858107AB1EC85E6B41C8AACF846E86789051D37998F7B9022D759B",
+ "9B9F605F5A858107AB1EC85E6B41C8AA582CA3511EDDFB74F02F3A6598980BB9",
+ "9B9F605F5A858107AB1EC85E6B41C8AACF846E86789051D37998F7B9022D7598",
+ "000000000000000000000000000000000000000000000000000000000000805a",
+ "0000000000000000000000000000000000000000000000000000000000000000",
+ "41ECE55743711A8C3CBF3783CD08C0EE4D4DC440D4641A8F366E550DFDB3BB67",
+ ),
+ "GostR3410_2012_TC26_ParamSetA": (
+ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDC7",
+ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF27E69532F48D89116FF22B8D4E0560609B4B38ABFAD2B85DCACDB1411F10B275",
+ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDC4",
+ "E8C2505DEDFC86DDC1BD0B2B6667F1DA34B82574761CB0E879BD081CFD0B6265EE3CB090F30D27614CB4574010DA90DD862EF9D4EBEE4761503190785A71C760",
+ "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003",
+ "7503CFE87A836AE3A61B8816E25450E6CE5E1C93ACF1ABC1778064FDCBEFA921DF1626BE4FD036E93D75E6A50E3A41E98028FE5FC235F5B889A589CB5215F2A4",
+ ),
+ "GostR3410_2012_TC26_ParamSetB": (
+ "8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006F",
+ "800000000000000000000000000000000000000000000000000000000000000149A1EC142565A545ACFDB77BD9D40CFA8B996712101BEA0EC6346C54374F25BD",
+ "8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006C",
+ "687D1B459DC841457E3E06CF6F5E2517B97C7D614AF138BCBF85DC806C4B289F3E965D2DB1416D217F8B276FAD1AB69C50F78BEE1FA3106EFB8CCBC7C5140116",
+ "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002",
+ "1A8F7EDA389B094C2C071E3647A8940F3C123B697578C213BE6DD9E6C8EC7335DCB228FD1EDF4A39152CBCAAF8C0398828041055F94CEEEC7E21340780FE41BD"
+ ),
+}
+for c, params in CURVE_PARAMS.items():
+ CURVE_PARAMS[c] = [hexdec(param) for param in params]
+
+
+class GOST3410Curve(object):
+ """ GOST 34.10 validated curve
+
+ >>> p, q, a, b, x, y = CURVE_PARAMS["GostR3410_2001_TestParamSet"]
+ >>> curve = GOST3410Curve(p, q, a, b, x, y)
+ >>> priv = bytes2long(urandom(32))
+ >>> signature = sign(curve, priv, GOST341194(data).digest())
+ >>> pubX, pubY = public_key(curve, priv)
+ >>> verify(curve, pubX, pubY, GOST341194(data).digest(), signature)
+ True
+ """
+ def __init__(self, p, q, a, b, x, y):
+ self.p = bytes2long(p)
+ self.q = bytes2long(q)
+ self.a = bytes2long(a)
+ self.b = bytes2long(b)
+ self.x = bytes2long(x)
+ self.y = bytes2long(y)
+ r1 = self.y * self.y % self.p
+ r2 = ((self.x * self.x + self.a) * self.x + self.b) % self.p
+ if r2 < 0:
+ r2 += self.p
+ if r1 != r2:
+ raise ValueError("Invalid parameters")
+
+ def _pos(self, v):
+ if v < 0:
+ return v + self.p
+ return v
+
+ def _add(self, p1x, p1y, p2x, p2y):
+ if p1x == p2x and p1y == p2y:
+ # double
+ t = ((3 * p1x * p1x + self.a) * modinvert(2 * p1y, self.p)) % self.p
+ else:
+ tx = self._pos(p2x - p1x) % self.p
+ ty = self._pos(p2y - p1y) % self.p
+ t = (ty * modinvert(tx, self.p)) % self.p
+ tx = self._pos(t * t - p1x - p2x) % self.p
+ ty = self._pos(t * (p1x - tx) - p1y) % self.p
+ return tx, ty
+
+ def exp(self, degree, x=None, y=None):
+ x = x or self.x
+ y = y or self.y
+ tx = x
+ ty = y
+ degree -= 1
+ if degree == 0:
+ raise ValueError("Bad degree value")
+ while degree != 0:
+ if degree & 1 == 1:
+ tx, ty = self._add(tx, ty, x, y)
+ degree = degree >> 1
+ x, y = self._add(x, y, x, y)
+ return tx, ty
+
+
+def public_key(curve, private_key):
+ """ Generate public key from the private one
+
+ :param GOST3410Curve curve: curve to use
+ :param long private_key: private key
+ :return: public key's parts, X and Y
+ :rtype: (long, long)
+ """
+ return curve.exp(private_key)
+
+
+def kek(curve, private_key, ukm, pubkey):
+ """ Make Diffie-Hellman computation
+
+ :param GOST3410Curve curve: curve to use
+ :param long private_key: private key
+ :param ukm: UKM value (VKO-factor)
+ :type ukm: bytes, 8 bytes
+ :param pubkey: public key's part
+ :type pubkey: (long, long)
+ :return: Key Encryption Key (shared key)
+ :rtype: bytes, 32 bytes
+
+ Shared Key Encryption Key computation is based on
+ :rfc:`4357` VKO GOST 34.10-2001 with little-endian
+ hash output.
+ """
+ key = curve.exp(private_key, pubkey[0], pubkey[1])
+ key = curve.exp(bytes2long(24 * b'\x00' + ukm), key[0], key[1])
+ return GOST341194(
+ (long2bytes(key[1]) + long2bytes(key[0]))[::-1],
+ "GostR3411_94_CryptoProParamSet"
+ ).digest()[::-1]
+
+
+def sign(curve, private_key, digest, size=SIZE_3410_2001):
+ """ Calculate signature for provided digest
+
+ :param GOST3410Curve curve: curve to use
+ :param long private_key: private key
+ :param digest: digest for signing
+ :type digest: bytes, 32 bytes
+ :param size: signature size
+ :type size: 32 (for 34.10-2001) or 64 (for 34.10-2012)
+ :return: signature
+ :rtype: bytes, 64 bytes
+ """
+ if len(digest) != size:
+ raise ValueError("Invalid digest length")
+ q = curve.q
+ e = bytes2long(digest) % q
+ if e == 0:
+ e = 1
+ while True:
+ k = bytes2long(urandom(size)) % q
+ if k == 0:
+ continue
+ r, _ = curve.exp(k)
+ r %= q
+ if r == 0:
+ continue
+ d = private_key * r
+ k *= e
+ s = (d + k) % q
+ if s == 0:
+ continue
+ break
+ return long2bytes(s, size) + long2bytes(r, size)
+
+
+def verify(curve, pubkeyX, pubkeyY, digest, signature, size=SIZE_3410_2001):
+ """ Verify provided digest with the signature
+
+ :param GOST3410Curve curve: curve to use
+ :param long pubkeyX: public key's X
+ :param long pubkeyY: public key's Y
+ :param digest: digest needed to check
+ :type digest: bytes, 32 bytes
+ :param signature: signature to verify with
+ :type signature: bytes, 64 bytes
+ :param size: signature size
+ :type size: 32 (for 34.10-2001) or 64 (for 34.10-2012)
+ :rtype: bool
+ """
+ if len(digest) != size:
+ raise ValueError("Invalid digest length")
+ if len(signature) != size * 2:
+ raise ValueError("Invalid signature length")
+ q = curve.q
+ p = curve.p
+ s = bytes2long(signature[:size])
+ r = bytes2long(signature[size:])
+ if r <= 0 or r >= q or s <= 0 or s >= q:
+ return False
+ e = bytes2long(digest) % curve.q
+ if e == 0:
+ e = 1
+ v = modinvert(e, q)
+ z1 = s * v % q
+ z2 = q - r * v % q
+ p1x, p1y = curve.exp(z1)
+ q1x, q1y = curve.exp(z2, pubkeyX, pubkeyY)
+ lm = q1x - p1x
+ if lm < 0:
+ lm += p
+ lm = modinvert(lm, p)
+ z1 = q1y - p1y
+ lm = lm * z1 % p
+ lm = lm * lm % p
+ lm = lm - p1x - q1x
+ lm = lm % p
+ if lm < 0:
+ lm += p
+ lm %= q
+ # This is not constant time comparison!
+ return lm == r
--- /dev/null
+# coding: utf-8
+# PyGOST -- Pure Python GOST cryptographic functions library
+# Copyright (C) 2015-2016 Sergey Matveev <stargrave@stargrave.org>
+#
+# 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 <http://www.gnu.org/licenses/>.
+""" GOST R 34.11-2012 (Streebog) hash function
+
+This is implementation of :rfc:`6986`. Most function and variable names are
+taken according to specification's terminology.
+"""
+
+from copy import copy
+from struct import pack
+from struct import unpack
+
+from pygost.iface import PEP247
+from pygost.utils import hexdec
+from pygost.utils import hexenc
+from pygost.utils import strxor
+from pygost.utils import xrange
+
+
+BLOCKSIZE = 64
+Pi = bytearray((
+ 252, 238, 221, 17, 207, 110, 49, 22, 251, 196, 250,
+ 218, 35, 197, 4, 77, 233, 119, 240, 219, 147, 46,
+ 153, 186, 23, 54, 241, 187, 20, 205, 95, 193, 249,
+ 24, 101, 90, 226, 92, 239, 33, 129, 28, 60, 66,
+ 139, 1, 142, 79, 5, 132, 2, 174, 227, 106, 143,
+ 160, 6, 11, 237, 152, 127, 212, 211, 31, 235, 52,
+ 44, 81, 234, 200, 72, 171, 242, 42, 104, 162, 253,
+ 58, 206, 204, 181, 112, 14, 86, 8, 12, 118, 18,
+ 191, 114, 19, 71, 156, 183, 93, 135, 21, 161, 150,
+ 41, 16, 123, 154, 199, 243, 145, 120, 111, 157, 158,
+ 178, 177, 50, 117, 25, 61, 255, 53, 138, 126, 109,
+ 84, 198, 128, 195, 189, 13, 87, 223, 245, 36, 169,
+ 62, 168, 67, 201, 215, 121, 214, 246, 124, 34, 185,
+ 3, 224, 15, 236, 222, 122, 148, 176, 188, 220, 232,
+ 40, 80, 78, 51, 10, 74, 167, 151, 96, 115, 30,
+ 0, 98, 68, 26, 184, 56, 130, 100, 159, 38, 65,
+ 173, 69, 70, 146, 39, 94, 85, 47, 140, 163, 165,
+ 125, 105, 213, 149, 59, 7, 88, 179, 64, 134, 172,
+ 29, 247, 48, 55, 107, 228, 136, 217, 231, 137, 225,
+ 27, 131, 73, 76, 63, 248, 254, 141, 83, 170, 144,
+ 202, 216, 133, 97, 32, 113, 103, 164, 45, 43, 9,
+ 91, 203, 155, 37, 208, 190, 229, 108, 82, 89, 166,
+ 116, 210, 230, 244, 180, 192, 209, 102, 175, 194, 57,
+ 75, 99, 182,
+))
+
+A = [unpack(">Q", hexdec(s))[0] for s in (
+ "8e20faa72ba0b470", "47107ddd9b505a38", "ad08b0e0c3282d1c", "d8045870ef14980e",
+ "6c022c38f90a4c07", "3601161cf205268d", "1b8e0b0e798c13c8", "83478b07b2468764",
+ "a011d380818e8f40", "5086e740ce47c920", "2843fd2067adea10", "14aff010bdd87508",
+ "0ad97808d06cb404", "05e23c0468365a02", "8c711e02341b2d01", "46b60f011a83988e",
+ "90dab52a387ae76f", "486dd4151c3dfdb9", "24b86a840e90f0d2", "125c354207487869",
+ "092e94218d243cba", "8a174a9ec8121e5d", "4585254f64090fa0", "accc9ca9328a8950",
+ "9d4df05d5f661451", "c0a878a0a1330aa6", "60543c50de970553", "302a1e286fc58ca7",
+ "18150f14b9ec46dd", "0c84890ad27623e0", "0642ca05693b9f70", "0321658cba93c138",
+ "86275df09ce8aaa8", "439da0784e745554", "afc0503c273aa42a", "d960281e9d1d5215",
+ "e230140fc0802984", "71180a8960409a42", "b60c05ca30204d21", "5b068c651810a89e",
+ "456c34887a3805b9", "ac361a443d1c8cd2", "561b0d22900e4669", "2b838811480723ba",
+ "9bcf4486248d9f5d", "c3e9224312c8c1a0", "effa11af0964ee50", "f97d86d98a327728",
+ "e4fa2054a80b329c", "727d102a548b194e", "39b008152acb8227", "9258048415eb419d",
+ "492c024284fbaec0", "aa16012142f35760", "550b8e9e21f7a530", "a48b474f9ef5dc18",
+ "70a6a56e2440598e", "3853dc371220a247", "1ca76e95091051ad", "0edd37c48a08a6d8",
+ "07e095624504536c", "8d70c431ac02a736", "c83862965601dd1b", "641c314b2b8ee083",
+)]
+
+Tau = (
+ 0, 8, 16, 24, 32, 40, 48, 56,
+ 1, 9, 17, 25, 33, 41, 49, 57,
+ 2, 10, 18, 26, 34, 42, 50, 58,
+ 3, 11, 19, 27, 35, 43, 51, 59,
+ 4, 12, 20, 28, 36, 44, 52, 60,
+ 5, 13, 21, 29, 37, 45, 53, 61,
+ 6, 14, 22, 30, 38, 46, 54, 62,
+ 7, 15, 23, 31, 39, 47, 55, 63,
+)
+
+C = [hexdec("".join(s))[::-1] for s in (
+ (
+ "b1085bda1ecadae9ebcb2f81c0657c1f",
+ "2f6a76432e45d016714eb88d7585c4fc",
+ "4b7ce09192676901a2422a08a460d315",
+ "05767436cc744d23dd806559f2a64507",
+ ),
+ (
+ "6fa3b58aa99d2f1a4fe39d460f70b5d7",
+ "f3feea720a232b9861d55e0f16b50131",
+ "9ab5176b12d699585cb561c2db0aa7ca",
+ "55dda21bd7cbcd56e679047021b19bb7",
+ ),
+ (
+ "f574dcac2bce2fc70a39fc286a3d8435",
+ "06f15e5f529c1f8bf2ea7514b1297b7b",
+ "d3e20fe490359eb1c1c93a376062db09",
+ "c2b6f443867adb31991e96f50aba0ab2",
+ ),
+ (
+ "ef1fdfb3e81566d2f948e1a05d71e4dd",
+ "488e857e335c3c7d9d721cad685e353f",
+ "a9d72c82ed03d675d8b71333935203be",
+ "3453eaa193e837f1220cbebc84e3d12e",
+ ),
+ (
+ "4bea6bacad4747999a3f410c6ca92363",
+ "7f151c1f1686104a359e35d7800fffbd",
+ "bfcd1747253af5a3dfff00b723271a16",
+ "7a56a27ea9ea63f5601758fd7c6cfe57",
+ ),
+ (
+ "ae4faeae1d3ad3d96fa4c33b7a3039c0",
+ "2d66c4f95142a46c187f9ab49af08ec6",
+ "cffaa6b71c9ab7b40af21f66c2bec6b6",
+ "bf71c57236904f35fa68407a46647d6e",
+ ),
+ (
+ "f4c70e16eeaac5ec51ac86febf240954",
+ "399ec6c7e6bf87c9d3473e33197a93c9",
+ "0992abc52d822c3706476983284a0504",
+ "3517454ca23c4af38886564d3a14d493",
+ ),
+ (
+ "9b1f5b424d93c9a703e7aa020c6e4141",
+ "4eb7f8719c36de1e89b4443b4ddbc49a",
+ "f4892bcb929b069069d18d2bd1a5c42f",
+ "36acc2355951a8d9a47f0dd4bf02e71e",
+ ),
+ (
+ "378f5a541631229b944c9ad8ec165fde",
+ "3a7d3a1b258942243cd955b7e00d0984",
+ "800a440bdbb2ceb17b2b8a9aa6079c54",
+ "0e38dc92cb1f2a607261445183235adb",
+ ),
+ (
+ "abbedea680056f52382ae548b2e4f3f3",
+ "8941e71cff8a78db1fffe18a1b336103",
+ "9fe76702af69334b7a1e6c303b7652f4",
+ "3698fad1153bb6c374b4c7fb98459ced",
+ ),
+ (
+ "7bcd9ed0efc889fb3002c6cd635afe94",
+ "d8fa6bbbebab07612001802114846679",
+ "8a1d71efea48b9caefbacd1d7d476e98",
+ "dea2594ac06fd85d6bcaa4cd81f32d1b",
+ ),
+ (
+ "378ee767f11631bad21380b00449b17a",
+ "cda43c32bcdf1d77f82012d430219f9b",
+ "5d80ef9d1891cc86e71da4aa88e12852",
+ "faf417d5d9b21b9948bc924af11bd720",
+ ),
+)]
+
+
+def add512bit(a, b):
+ """ Add two 512 integers
+ """
+ a = bytearray(a)
+ b = bytearray(b)
+ cb = 0
+ res = bytearray(64)
+ for i in range(64):
+ cb = a[i] + b[i] + (cb >> 8)
+ res[i] = cb & 0xff
+ return res
+
+
+def g(n, hsh, msg):
+ res = E(LPS(strxor(hsh[:8], pack("<Q", n)) + hsh[8:]), msg)
+ return strxor(strxor(res, hsh), msg)
+
+
+def E(k, msg):
+ for i in range(12):
+ msg = LPS(strxor(k, msg))
+ k = LPS(strxor(k, C[i]))
+ return strxor(k, msg)
+
+
+def LPS(data):
+ return L(PS(bytearray(data)))
+
+
+def PS(data):
+ res = bytearray(BLOCKSIZE)
+ for i in range(BLOCKSIZE):
+ res[Tau[i]] = Pi[data[i]]
+ return res
+
+
+def L(data):
+ res = []
+ for i in range(8):
+ val = unpack("<Q", data[i * 8:i * 8 + 8])[0]
+ res64 = 0
+ for j in range(BLOCKSIZE):
+ if val & 0x8000000000000000:
+ res64 ^= A[j]
+ val <<= 1
+ res.append(pack("<Q", res64))
+ return b''.join(res)
+
+
+class GOST34112012(PEP247):
+ """ GOST 34.11-2012 big-endian hash
+
+ >>> m = GOST34112012(digest_size=32)
+ >>> m.update("foo")
+ >>> m.update("bar")
+ >>> m.hexdigest()
+ 'e3c9fd89226d93b489a9fe27d686806e24a514e3787bca053c698ec4616ceb78'
+ """
+ block_size = BLOCKSIZE
+
+ def __init__(self, data=b'', digest_size=64):
+ """
+ :param digest_size: hash digest size to compute
+ :type digest_size: 32 or 64 bytes
+ """
+ self.data = data
+ self._digest_size = digest_size
+
+ def copy(self):
+ return GOST34112012(copy(self.data), self.digest_size)
+
+ @property
+ def digest_size(self):
+ return self._digest_size
+
+ def update(self, data):
+ """ Append data that has to be hashed
+ """
+ self.data += data
+
+ def digest(self):
+ """ Get hash of the provided data
+ """
+ hsh = BLOCKSIZE * (b'\x01' if self.digest_size == 32 else b'\x00')
+ chk = bytearray(BLOCKSIZE * b'\x00')
+ n = 0
+ data = self.data
+ for i in xrange(0, len(data) // BLOCKSIZE * BLOCKSIZE, BLOCKSIZE):
+ block = data[i:i + BLOCKSIZE]
+ hsh = g(n, hsh, block)
+ chk = add512bit(chk, block)
+ n += 512
+
+ # Padding
+ padblock_size = len(data) * 8 - n
+ data += b'\x01'
+ padlen = BLOCKSIZE - len(data) % BLOCKSIZE
+ if padlen != BLOCKSIZE:
+ data += b'\x00' * padlen
+
+ hsh = g(n, hsh, data[-BLOCKSIZE:])
+ n += padblock_size
+ chk = add512bit(chk, data[-BLOCKSIZE:])
+ hsh = g(0, hsh, pack("<Q", n) + 56 * b'\x00')
+ hsh = g(0, hsh, chk)
+ return hsh[-self._digest_size:]
+
+ def hexdigest(self):
+ return hexenc(self.digest())
+
+
+def new(data=b'', digest_size=64):
+ return GOST34112012(data, digest_size)
--- /dev/null
+# coding: utf-8
+# PyGOST -- Pure Python GOST cryptographic functions library
+# Copyright (C) 2015-2016 Sergey Matveev <stargrave@stargrave.org>
+#
+# 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 <http://www.gnu.org/licenses/>.
+""" GOST R 34.11-94 hash function
+
+This is implementation of :rfc:`5831`. Most function and variable names are
+taken according to specification's terminology.
+"""
+
+from copy import copy
+from struct import pack
+
+from pygost.gost28147 import addmod
+from pygost.gost28147 import block2ns
+from pygost.gost28147 import encrypt
+from pygost.gost28147 import ns2block
+from pygost.gost28147 import validate_sbox
+from pygost.iface import PEP247
+from pygost.utils import hexdec
+from pygost.utils import hexenc
+from pygost.utils import strxor
+from pygost.utils import xrange
+
+
+DEFAULT_SBOX = "GostR3411_94_TestParamSet"
+BLOCKSIZE = 32
+C2 = 32 * b'\x00'
+C3 = hexdec(b'ff00ffff000000ffff0000ff00ffff0000ff00ff00ff00ffff00ff00ff00ff00')
+C4 = 32 * b'\x00'
+digest_size = 32
+
+
+def A(x):
+ x4, x3, x2, x1 = x[0:8], x[8:16], x[16:24], x[24:32]
+ return b''.join((strxor(x1, x2), x4, x3, x2))
+
+
+def P(x):
+ return bytearray((
+ x[0], x[8], x[16], x[24], x[1], x[9], x[17], x[25], x[2],
+ x[10], x[18], x[26], x[3], x[11], x[19], x[27], x[4], x[12],
+ x[20], x[28], x[5], x[13], x[21], x[29], x[6], x[14], x[22],
+ x[30], x[7], x[15], x[23], x[31],
+ ))
+
+
+def _chi(Y):
+ """ Chi function
+
+ This is some kind of LFSR.
+ """
+ (y16, y15, y14, y13, y12, y11, y10, y9, y8, y7, y6, y5, y4, y3, y2, y1) = (
+ Y[0:2], Y[2:4], Y[4:6], Y[6:8], Y[8:10], Y[10:12], Y[12:14],
+ Y[14:16], Y[16:18], Y[18:20], Y[20:22], Y[22:24], Y[24:26],
+ Y[26:28], Y[28:30], Y[30:32],
+ )
+ by1, by2, by3, by4, by13, by16, byx = (
+ bytearray(y1), bytearray(y2), bytearray(y3), bytearray(y4),
+ bytearray(y13), bytearray(y16), bytearray(2),
+ )
+ byx[0] = by1[0] ^ by2[0] ^ by3[0] ^ by4[0] ^ by13[0] ^ by16[0]
+ byx[1] = by1[1] ^ by2[1] ^ by3[1] ^ by4[1] ^ by13[1] ^ by16[1]
+ return b''.join((
+ bytes(byx), y16, y15, y14, y13, y12, y11, y10, y9, y8, y7, y6, y5, y4, y3, y2
+ ))
+
+
+def _step(hin, m, sbox):
+ """ Step function
+
+ H_out = f(H_in, m)
+ """
+ # Generate keys
+ u = hin
+ v = m
+ w = strxor(hin, m)
+ k1 = P(w)
+
+ u = strxor(A(u), C2)
+ v = A(A(v))
+ w = strxor(u, v)
+ k2 = P(w)
+
+ u = strxor(A(u), C3)
+ v = A(A(v))
+ w = strxor(u, v)
+ k3 = P(w)
+
+ u = strxor(A(u), C4)
+ v = A(A(v))
+ w = strxor(u, v)
+ k4 = P(w)
+
+ # Encipher
+ h4, h3, h2, h1 = hin[0:8], hin[8:16], hin[16:24], hin[24:32]
+ s1 = ns2block(encrypt(sbox, k1[::-1], block2ns(h1[::-1])))[::-1]
+ s2 = ns2block(encrypt(sbox, k2[::-1], block2ns(h2[::-1])))[::-1]
+ s3 = ns2block(encrypt(sbox, k3[::-1], block2ns(h3[::-1])))[::-1]
+ s4 = ns2block(encrypt(sbox, k4[::-1], block2ns(h4[::-1])))[::-1]
+ s = b''.join((s4, s3, s2, s1))
+
+ # Permute
+ # H_out = chi^61(H_in XOR chi(m XOR chi^12(S)))
+ x = s
+ for _ in range(12):
+ x = _chi(x)
+ x = strxor(x, m)
+ x = _chi(x)
+ x = strxor(hin, x)
+ for _ in range(61):
+ x = _chi(x)
+ return x
+
+
+class GOST341194(PEP247):
+ """ GOST 34.11-94 little-endian hash
+
+ >>> m = GOST341194()
+ >>> m.update("foo")
+ >>> m.update("bar")
+ >>> m.hexdigest()
+ '3bd8a3a35917871dfa0d49f9e73e7c57eea028dc061133eb560849ea20c133af'
+ >>> GOST341194("foobar").hexdigest()
+ '3bd8a3a35917871dfa0d49f9e73e7c57eea028dc061133eb560849ea20c133af'
+ """
+ block_size = BLOCKSIZE
+ digest_size = BLOCKSIZE
+
+ def __init__(self, data=b'', sbox=DEFAULT_SBOX):
+ """
+ :param bytes data: provide initial data
+ :param bytes sbox: S-box to use
+ """
+ validate_sbox(sbox)
+ self.data = data
+ self.sbox = sbox
+
+ def copy(self):
+ return GOST341194(copy(self.data), self.sbox)
+
+ def update(self, data):
+ """ Append data that has to be hashed
+ """
+ self.data += data
+
+ def digest(self):
+ """ Get hash of the provided data
+ """
+ l = 0
+ checksum = 0
+ h = 32 * b'\x00'
+ m = self.data
+ for i in xrange(0, len(m), BLOCKSIZE):
+ part = m[i:i + BLOCKSIZE][::-1]
+ l += len(part) * 8
+ checksum = addmod(checksum, int(hexenc(part), 16), 2 ** 256)
+ if len(part) < BLOCKSIZE:
+ part = b'\x00' * (BLOCKSIZE - len(part)) + part
+ h = _step(h, part, self.sbox)
+ h = _step(h, 24 * b'\x00' + pack(">Q", l), self.sbox)
+
+ checksum = hex(checksum)[2:].rstrip("L")
+ if len(checksum) % 2 != 0:
+ checksum = "0" + checksum
+ checksum = hexdec(checksum)
+ checksum = b'\x00' * (BLOCKSIZE - len(checksum)) + checksum
+ h = _step(h, checksum, self.sbox)
+ return h
+
+ def hexdigest(self):
+ return hexenc(self.digest())
+
+
+def new(data=b'', sbox=DEFAULT_SBOX):
+ return GOST341194(data, sbox)
--- /dev/null
+# coding: utf-8
+# PyGOST -- Pure Python GOST cryptographic functions library
+# Copyright (C) 2015-2016 Sergey Matveev <stargrave@stargrave.org>
+#
+# 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 <http://www.gnu.org/licenses/>.
+"""GOST 34.12-2015 128-bit block cipher Кузнечик (Kuznechik)
+
+:rfc:`7801`. Pay attention that 34.12-2015 also defines 64-bit block
+cipher Магма (Magma) -- it is **not** implemented here.
+
+Several precalculations are performed during this module importing.
+"""
+
+from pygost.utils import strxor
+from pygost.utils import xrange
+
+
+LC = bytearray((
+ 148, 32, 133, 16, 194, 192, 1, 251, 1, 192, 194, 16, 133, 32, 148, 1,
+))
+PI = bytearray((
+ 252, 238, 221, 17, 207, 110, 49, 22, 251, 196, 250, 218, 35, 197, 4, 77,
+ 233, 119, 240, 219, 147, 46, 153, 186, 23, 54, 241, 187, 20, 205, 95, 193,
+ 249, 24, 101, 90, 226, 92, 239, 33, 129, 28, 60, 66, 139, 1, 142, 79, 5,
+ 132, 2, 174, 227, 106, 143, 160, 6, 11, 237, 152, 127, 212, 211, 31, 235,
+ 52, 44, 81, 234, 200, 72, 171, 242, 42, 104, 162, 253, 58, 206, 204, 181,
+ 112, 14, 86, 8, 12, 118, 18, 191, 114, 19, 71, 156, 183, 93, 135, 21, 161,
+ 150, 41, 16, 123, 154, 199, 243, 145, 120, 111, 157, 158, 178, 177, 50, 117,
+ 25, 61, 255, 53, 138, 126, 109, 84, 198, 128, 195, 189, 13, 87, 223, 245,
+ 36, 169, 62, 168, 67, 201, 215, 121, 214, 246, 124, 34, 185, 3, 224, 15,
+ 236, 222, 122, 148, 176, 188, 220, 232, 40, 80, 78, 51, 10, 74, 167, 151,
+ 96, 115, 30, 0, 98, 68, 26, 184, 56, 130, 100, 159, 38, 65, 173, 69, 70,
+ 146, 39, 94, 85, 47, 140, 163, 165, 125, 105, 213, 149, 59, 7, 88, 179, 64,
+ 134, 172, 29, 247, 48, 55, 107, 228, 136, 217, 231, 137, 225, 27, 131, 73,
+ 76, 63, 248, 254, 141, 83, 170, 144, 202, 216, 133, 97, 32, 113, 103, 164,
+ 45, 43, 9, 91, 203, 155, 37, 208, 190, 229, 108, 82, 89, 166, 116, 210, 230,
+ 244, 180, 192, 209, 102, 175, 194, 57, 75, 99, 182,
+))
+
+########################################################################
+# Precalculate inverted PI value as a performance optimization.
+# Actually it can be computed only once and saved on the disk.
+########################################################################
+PIinv = bytearray(256)
+for x in xrange(256):
+ PIinv[PI[x]] = x
+
+
+def gf(a, b):
+ c = 0
+ while b:
+ if b & 1:
+ c ^= a
+ if a & 0x80:
+ a = (a << 1) ^ 0x1C3
+ else:
+ a <<= 1
+ b >>= 1
+ return c
+
+########################################################################
+# Precalculate all possible gf(byte, byte) values as a performance
+# optimization.
+# Actually it can be computed only once and saved on the disk.
+########################################################################
+GF = [bytearray(256) for _ in xrange(256)]
+for x in xrange(256):
+ for y in xrange(256):
+ GF[x][y] = gf(x, y)
+
+
+def L(blk, rounds=16):
+ for _ in range(rounds):
+ t = blk[15]
+ for i in range(14, -1, -1):
+ blk[i + 1] = blk[i]
+ t ^= GF[blk[i]][LC[i]]
+ blk[0] = t
+ return blk
+
+
+def Linv(blk):
+ for _ in range(16):
+ t = blk[0]
+ for i in range(15):
+ blk[i] = blk[i + 1]
+ t ^= GF[blk[i]][LC[i]]
+ blk[15] = t
+ return blk
+
+########################################################################
+# Precalculate values of the C -- it does not depend on key.
+# Actually it can be computed only once and saved on the disk.
+########################################################################
+C = []
+for x in range(1, 33):
+ y = bytearray(16)
+ y[15] = x
+ C.append(L(y))
+
+
+def lp(blk):
+ return L([PI[v] for v in blk])
+
+
+class GOST3412Kuz(object):
+ """GOST 34.12-2015 128-bit block cipher Кузнечик (Kuznechik)
+ """
+ def __init__(self, key):
+ """
+ :param key: encryption/decryption key
+ :type key: bytes, 32 bytes
+
+ Key scheduling (roundkeys precomputation) is performed here.
+ """
+ kr0 = bytearray(key[:16])
+ kr1 = bytearray(key[16:])
+ self.ks = [kr0, kr1]
+ for i in range(4):
+ for j in range(8):
+ k = lp(bytearray(strxor(C[8 * i + j], kr0)))
+ kr0, kr1 = [strxor(k, kr1), kr0]
+ self.ks.append(kr0)
+ self.ks.append(kr1)
+
+ def encrypt(self, blk):
+ blk = bytearray(blk)
+ for i in range(9):
+ blk = lp(bytearray(strxor(self.ks[i], blk)))
+ return bytes(strxor(self.ks[9], blk))
+
+ def decrypt(self, blk):
+ blk = bytearray(blk)
+ for i in range(9, 0, -1):
+ blk = [PIinv[v] for v in Linv(bytearray(strxor(self.ks[i], blk)))]
+ return bytes(strxor(self.ks[0], blk))
--- /dev/null
+# coding: utf-8
+# PyGOST -- Pure Python GOST cryptographic functions library
+# Copyright (C) 2015-2016 Sergey Matveev <stargrave@stargrave.org>
+#
+# 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 <http://www.gnu.org/licenses/>.
+""" GOST R 34.13-2015: Modes of operation for block ciphers
+
+This module currently includes only padding methods.
+"""
+
+
+def pad_size(data_size, blocksize):
+ """Calculate required pad size to full up BLOCKSIZE
+ """
+ if data_size < blocksize:
+ return blocksize - data_size
+ if data_size % blocksize == 0:
+ return 0
+ return blocksize - data_size % blocksize
+
+
+def pad1(data, blocksize):
+ """Padding method 1
+
+ Just fill up with zeros if necessary.
+ """
+ return data + b'\x00' * pad_size(len(data), blocksize)
+
+
+def pad2(data, blocksize):
+ """Padding method 2 (also known as ISO/IEC 7816-4)
+
+ Add one bit and then fill up with zeros.
+ """
+ return data + b'\x80' + b'\x00' * pad_size(len(data) + 1, blocksize)
+
+
+def pad3(data, blocksize):
+ """Padding method 3
+ """
+ if pad_size(len(data), blocksize) == 0:
+ return data
+ return pad2(data, blocksize)
--- /dev/null
+from abc import ABCMeta
+from abc import abstractmethod
+
+
+# This function is taken from six package as is
+def add_metaclass(metaclass):
+ """Class decorator for creating a class with a metaclass."""
+ def wrapper(cls):
+ orig_vars = cls.__dict__.copy()
+ slots = orig_vars.get('__slots__')
+ if slots is not None:
+ if isinstance(slots, str):
+ slots = [slots]
+ for slots_var in slots:
+ orig_vars.pop(slots_var)
+ orig_vars.pop('__dict__', None)
+ orig_vars.pop('__weakref__', None)
+ return metaclass(cls.__name__, cls.__bases__, orig_vars)
+ return wrapper
+
+
+@add_metaclass(ABCMeta)
+class PEP247(object):
+ @property
+ @abstractmethod
+ def digest_size(self):
+ """The size of the digest produced by the hashing objects.
+ """
+
+ @abstractmethod
+ def copy(self):
+ """Return a separate copy of this hashing object.
+ """
+
+ @abstractmethod
+ def update(self, data):
+ """Hash data into the current state of the hashing object.
+ """
+
+ @abstractmethod
+ def digest(self):
+ """Return the hash value as a string containing 8-bit data.
+ """
+
+ @abstractmethod
+ def hexdigest(self):
+ """Return the hash value as a string containing hexadecimal digits.
+ """
--- /dev/null
+from typing import Callable
+from typing import Sequence
+from typing import Tuple
+
+
+Words = Tuple[int, int]
+
+
+def block2ns(data: bytes) -> Words: ...
+
+
+def ns2block(ns: Words) -> bytes: ...
+
+
+def addmod(x: int, y: int, mod: int=...) -> int: ...
+
+
+def validate_key(key: bytes) -> None: ...
+
+
+def validate_iv(iv: bytes) -> None: ...
+
+
+def validate_sbox(sbox: str) -> None: ...
+
+
+def xcrypt(seq: Sequence[int], sbox: str, key: bytes, ns: Words) -> Words: ...
+
+
+def encrypt(sbox: str, key: bytes, ns: Words) -> Words: ...
+
+
+def decrypt(sbox: str, key: bytes, ns: Words) -> Words: ...
+
+
+def ecb(
+ key: bytes,
+ data: bytes,
+ action: Callable[[str, bytes, Words], Words],
+ sbox: str=...,
+) -> bytes: ...
+
+
+def cbc_encrypt(
+ key: bytes,
+ data: bytes,
+ iv: bytes=...,
+ pad: bool=...,
+ sbox: str=...,
+) -> bytes: ...
+
+
+def cbc_decrypt(
+ key: bytes,
+ data: bytes,
+ pad: bool=...,
+ sbox: str=...,
+) -> bytes: ...
+
+
+def cnt(
+ key: bytes,
+ data: bytes,
+ iv: bytes=...,
+ sbox: str=...,
+) -> bytes: ...
+
+
+def cfb_encrypt(
+ key: bytes,
+ data: bytes,
+ iv: bytes=...,
+ sbox: str=...,
+ mesh: bool=...,
+) -> bytes: ...
+
+
+def cfb_decrypt(
+ key: bytes,
+ data: bytes,
+ iv: bytes=...,
+ sbox: str=...,
+ mesh: bool=...,
+) -> bytes: ...
--- /dev/null
+class MAC:
+ def __init__(
+ self,
+ key: bytes,
+ data: bytes=...,
+ iv: bytes=...,
+ sbox: str=...,
+ ) -> None: ...
+
+ @property
+ def digest_size(self) -> int: ...
+
+ def copy(self) -> "MAC": ...
+
+ def update(self, data: bytes) -> None: ...
+
+ def digest(self) -> bytes: ...
+
+ def hexdigest(self) -> str: ...
--- /dev/null
+from typing import Dict
+from typing import Tuple
+
+
+CURVE_PARAMS = ... # type: Dict[str, Tuple[bytes, bytes, bytes, bytes, bytes, bytes]]
+
+
+class GOST3410Curve(object):
+ p = ... # type: int
+ q = ... # type: int
+ a = ... # type: int
+ b = ... # type: int
+ x = ... # type: int
+ y = ... # type: int
+
+ def __init__(
+ self, p: bytes, q: bytes, a: bytes, b: bytes, x: bytes, y: bytes
+ ) -> None: ...
+
+ def exp(self, degree: int, x: int=..., y: int=...) -> int: ...
+
+
+PublicKey = Tuple[int, int]
+
+
+def public_key(curve: GOST3410Curve, private_key: int) -> PublicKey: ...
+
+
+def kek(
+ curve: GOST3410Curve,
+ private_key: int,
+ ukm: bytes,
+ pubkey: PublicKey,
+) -> bytes: ...
+
+
+def sign(
+ curve: GOST3410Curve,
+ private_key: int,
+ digest: bytes,
+ size: int=...,
+) -> bytes: ...
+
+
+def verify(
+ curve: GOST3410Curve,
+ pubkeyX: int,
+ pubkeyY: int,
+ digest: bytes,
+ signature: bytes,
+ size: int=...,
+) -> bool: ...
--- /dev/null
+class GOST34112012:
+ def __init__(self, data: bytes=..., digest_size: int=...) -> None: ...
+
+ @property
+ def digest_size(self) -> int: ...
+
+ def copy(self) -> "GOST34112012": ...
+
+ def update(self, data: bytes) -> None: ...
+
+ def digest(self) -> bytes: ...
+
+ def hexdigest(self) -> str: ...
--- /dev/null
+class GOST341194:
+ def __init__(self, data: bytes=..., sbox: str=...) -> None: ...
+
+ @property
+ def digest_size(self) -> int: ...
+
+ def copy(self) -> "GOST341194": ...
+
+ def update(self, data: bytes) -> None: ...
+
+ def digest(self) -> bytes: ...
+
+ def hexdigest(self) -> str: ...
--- /dev/null
+class GOST3412Kuz(object):
+ def __init__(self, key: bytes) -> None: ...
+
+ def encrypt(self, blk: bytes) -> bytes: ...
+
+ def decrypt(self, blk: bytes) -> bytes: ...
--- /dev/null
+def pad_size(int, int) -> int: ...
+
+
+def pad1(bytes, int) -> bytes: ...
+
+
+def pad2(bytes, int) -> bytes: ...
+
+
+def pad3(bytes, int) -> bytes: ...
--- /dev/null
+from abc import ABCMeta
+from abc import abstractmethod
+
+
+class PEP247(metaclass=ABCMeta):
+ @abstractmethod
+ @property
+ def digest_size(self) -> int: ...
+
+ @abstractmethod
+ def copy(self) -> "PEP247": ...
+
+ @abstractmethod
+ def update(self, data: bytes) -> None: ...
+
+ @abstractmethod
+ def digest(self) -> bytes: ...
+
+ @abstractmethod
+ def hexdigest(self) -> str: ...
--- /dev/null
+from typing import AnyStr
+from typing import Optional
+
+
+def strxor(a: bytes, b: bytes) -> bytes: ...
+
+
+def hexdec(data: AnyStr) -> bytes: ...
+
+
+def hexenc(data: bytes) -> str: ...
+
+
+def bytes2long(raw: bytes) -> int: ...
+
+
+def long2bytes(n: int, size: int=...) -> bytes: ...
+
+
+def modinvert(a: int, n: int) -> int: ...
--- /dev/null
+def wrap_gost(ukm: bytes, kek: bytes, cek: bytes) -> bytes: ...
+
+
+def unwrap_gost(kek: bytes, data: bytes) -> bytes: ...
+
+
+def wrap_cryptopro(ukm: bytes, kek: bytes, cek: bytes) -> bytes: ...
+
+
+def unwrap_cryptopro(kek: bytes, data: bytes) -> bytes: ...
--- /dev/null
+from typing import Tuple
+
+
+SIZE_3410_2001 = ... # type: int
+SIZE_3410_2012 = ... # type: int
+
+
+def keypair_gen(
+ seed: bytes,
+ mode: int=...,
+ curve_params: str=...,
+) -> Tuple[bytes, bytes]: ...
+
+
+def sign_digest(
+ private_key: bytes,
+ digest: bytes,
+ mode: int=...,
+ curve_params: str=...,
+) -> bytes: ...
+
+
+def verify_digest(
+ public_key: bytes,
+ digest: bytes,
+ signature: bytes,
+ mode: int=...,
+ curve_params: str=...,
+) -> bool: ...
+
+
+def sign(
+ private_key: bytes,
+ data: bytes,
+ mode: int=...,
+ curve_params: str=...,
+) -> bytes: ...
+
+
+def verify(
+ public_key: bytes,
+ data: bytes,
+ signature: bytes,
+ mode: int=...,
+ curve_params: str=...,
+) -> bool: ...
--- /dev/null
+# coding: utf-8
+# PyGOST -- Pure Python GOST cryptographic functions library
+# Copyright (C) 2015-2016 Sergey Matveev <stargrave@stargrave.org>
+#
+# 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 <http://www.gnu.org/licenses/>.
+
+from os import urandom
+from unittest import TestCase
+
+from pygost.gost28147 import block2ns
+from pygost.gost28147 import cbc_decrypt
+from pygost.gost28147 import cbc_encrypt
+from pygost.gost28147 import cfb_decrypt
+from pygost.gost28147 import cfb_encrypt
+from pygost.gost28147 import cnt
+from pygost.gost28147 import DEFAULT_SBOX
+from pygost.gost28147 import ecb_decrypt
+from pygost.gost28147 import ecb_encrypt
+from pygost.gost28147 import encrypt
+from pygost.gost28147 import MESH_MAX_DATA
+from pygost.gost28147 import ns2block
+from pygost.utils import hexdec
+from pygost.utils import strxor
+
+
+class ECBTest(TestCase):
+ def test_gcl(self):
+ """ Test vectors from libgcl3
+ """
+ sbox = "Gost2814789_TestParamSet"
+ key = hexdec(b'0475f6e05038fbfad2c7c390edb3ca3d1547124291ae1e8a2f79cd9ed2bcefbd')
+ plaintext = bytes(bytearray((
+ 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
+ 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
+ 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
+ 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18,
+ 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20,
+ 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28,
+ 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30,
+ 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38,
+ 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40,
+ 0x4f, 0x4e, 0x4d, 0x4c, 0x4b, 0x4a, 0x49, 0x48,
+ 0x57, 0x56, 0x55, 0x54, 0x53, 0x52, 0x51, 0x50,
+ 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59, 0x58,
+ 0x67, 0x66, 0x65, 0x64, 0x63, 0x62, 0x61, 0x60,
+ 0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68,
+ 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70,
+ 0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a, 0x79, 0x78,
+ 0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80,
+ 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88,
+ 0x97, 0x96, 0x95, 0x94, 0x93, 0x92, 0x91, 0x90,
+ 0x9f, 0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98,
+ 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1, 0xa0,
+ 0xaf, 0xae, 0xad, 0xac, 0xab, 0xaa, 0xa9, 0xa8,
+ 0xb7, 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0,
+ 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8,
+ 0xc7, 0xc6, 0xc5, 0xc4, 0xc3, 0xc2, 0xc1, 0xc0,
+ 0xcf, 0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8,
+ 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1, 0xd0,
+ 0xdf, 0xde, 0xdd, 0xdc, 0xdb, 0xda, 0xd9, 0xd8,
+ 0xe7, 0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0,
+ 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9, 0xe8,
+ 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0,
+ 0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8,
+ )))
+ ciphertext = bytes(bytearray((
+ 0x4b, 0x8c, 0x4c, 0x98, 0x15, 0xf2, 0x4a, 0xea,
+ 0x1e, 0xc3, 0x57, 0x09, 0xb3, 0xbc, 0x2e, 0xd1,
+ 0xe0, 0xd1, 0xf2, 0x22, 0x65, 0x2d, 0x59, 0x18,
+ 0xf7, 0xdf, 0xfc, 0x80, 0x4b, 0xde, 0x5c, 0x68,
+ 0x46, 0x53, 0x75, 0x53, 0xa7, 0x46, 0x0d, 0xec,
+ 0x05, 0x1f, 0x1b, 0xd3, 0x0a, 0x63, 0x1a, 0xb7,
+ 0x78, 0xc4, 0x43, 0xe0, 0x5d, 0x3e, 0xa4, 0x0e,
+ 0x2d, 0x7e, 0x23, 0xa9, 0x1b, 0xc9, 0x02, 0xbc,
+ 0x21, 0x0c, 0x84, 0xcb, 0x0d, 0x0a, 0x07, 0xc8,
+ 0x7b, 0xd0, 0xfb, 0xb5, 0x1a, 0x14, 0x04, 0x5c,
+ 0xa2, 0x53, 0x97, 0x71, 0x2e, 0x5c, 0xc2, 0x8f,
+ 0x39, 0x3f, 0x6f, 0x52, 0xf2, 0x30, 0x26, 0x4e,
+ 0x8c, 0xe0, 0xd1, 0x01, 0x75, 0x6d, 0xdc, 0xd3,
+ 0x03, 0x79, 0x1e, 0xca, 0xd5, 0xc1, 0x0e, 0x12,
+ 0x53, 0x0a, 0x78, 0xe2, 0x0a, 0xb1, 0x1c, 0xea,
+ 0x3a, 0xf8, 0x55, 0xb9, 0x7c, 0xe1, 0x0b, 0xba,
+ 0xa0, 0xc8, 0x96, 0xeb, 0x50, 0x5a, 0xd3, 0x60,
+ 0x43, 0xa3, 0x0f, 0x98, 0xdb, 0xd9, 0x50, 0x6d,
+ 0x63, 0x91, 0xaf, 0x01, 0x40, 0xe9, 0x75, 0x5a,
+ 0x46, 0x5c, 0x1f, 0x19, 0x4a, 0x0b, 0x89, 0x9b,
+ 0xc4, 0xf6, 0xf8, 0xf5, 0x2f, 0x87, 0x3f, 0xfa,
+ 0x26, 0xd4, 0xf8, 0x25, 0xba, 0x1f, 0x98, 0x82,
+ 0xfc, 0x26, 0xaf, 0x2d, 0xc0, 0xf9, 0xc4, 0x58,
+ 0x49, 0xfa, 0x09, 0x80, 0x02, 0x62, 0xa4, 0x34,
+ 0x2d, 0xcb, 0x5a, 0x6b, 0xab, 0x61, 0x5d, 0x08,
+ 0xd4, 0x26, 0xe0, 0x08, 0x13, 0xd6, 0x2e, 0x02,
+ 0x2a, 0x37, 0xe8, 0xd0, 0xcf, 0x36, 0xf1, 0xc7,
+ 0xc0, 0x3f, 0x9b, 0x21, 0x60, 0xbd, 0x29, 0x2d,
+ 0x2e, 0x01, 0x48, 0x4e, 0xf8, 0x8f, 0x20, 0x16,
+ 0x8a, 0xbf, 0x82, 0xdc, 0x32, 0x7a, 0xa3, 0x18,
+ 0x69, 0xd1, 0x50, 0x59, 0x31, 0x91, 0xf2, 0x6c,
+ 0x5a, 0x5f, 0xca, 0x58, 0x9a, 0xb2, 0x2d, 0xb2,
+ )))
+ encrypted = ecb_encrypt(key, plaintext, sbox=sbox)
+ self.assertEqual(encrypted, ciphertext)
+ decrypted = ecb_decrypt(key, encrypted, sbox=sbox)
+ self.assertEqual(decrypted, plaintext)
+
+ def test_cryptopp(self):
+ """ Test vectors from Crypto++ 5.6.2
+ """
+ sbox = "AppliedCryptography"
+ data = (
+ (b'BE5EC2006CFF9DCF52354959F1FF0CBFE95061B5A648C10387069C25997C0672', b'0DF82802B741A292', b'07F9027DF7F7DF89'),
+ (b'B385272AC8D72A5A8B344BC80363AC4D09BF58F41F540624CBCB8FDCF55307D7', b'1354EE9C0A11CD4C', b'4FB50536F960A7B1'),
+ (b'AEE02F609A35660E4097E546FD3026B032CD107C7D459977ADF489BEF2652262', b'6693D492C4B0CC39', b'670034AC0FA811B5'),
+ (b'320E9D8422165D58911DFC7D8BBB1F81B0ECD924023BF94D9DF7DCF7801240E0', b'99E2D13080928D79', b'8118FF9D3B3CFE7D'),
+ (b'C9F703BBBFC63691BFA3B7B87EA8FD5E8E8EF384EF733F1A61AEF68C8FFA265F', b'D1E787749C72814C', b'A083826A790D3E0C'),
+ (b'728FEE32F04B4C654AD7F607D71C660C2C2670D7C999713233149A1C0C17A1F0', b'D4C05323A4F7A7B5', b'4D1F2E6B0D9DE2CE'),
+ (b'35FC96402209500FCFDEF5352D1ABB038FE33FC0D9D58512E56370B22BAA133B', b'8742D9A05F6A3AF6', b'2F3BB84879D11E52'),
+ (b'D416F630BE65B7FE150656183370E07018234EE5DA3D89C4CE9152A03E5BFB77', b'F86506DA04E41CB8', b'96F0A5C77A04F5CE'),
+ )
+ for key, pt, ct in data:
+ key = hexdec(key)
+ pt = hexdec(pt)
+ ct = hexdec(ct)
+ self.assertEqual(ecb_encrypt(key, pt, sbox=sbox), ct)
+
+ def test_cryptomanager(self):
+ """ Test vector from http://cryptomanager.com/tv.html
+ """
+ sbox = "GostR3411_94_TestParamSet"
+ key = hexdec(b'75713134B60FEC45A607BB83AA3746AF4FF99DA6D1B53B5B1B402A1BAA030D1B')
+ self.assertEqual(
+ ecb_encrypt(key, hexdec(b'1122334455667788'), sbox=sbox),
+ hexdec(b'03251E14F9D28ACB'),
+ )
+
+
+class CFBTest(TestCase):
+ def test_cryptomanager(self):
+ """ Test vector from http://cryptomanager.com/tv.html
+ """
+ key = hexdec(b'75713134B60FEC45A607BB83AA3746AF4FF99DA6D1B53B5B1B402A1BAA030D1B')
+ sbox = "GostR3411_94_TestParamSet"
+ self.assertEqual(
+ cfb_encrypt(
+ key,
+ hexdec(b'112233445566778899AABBCCDD800000'),
+ iv=hexdec(b'0102030405060708'),
+ sbox=sbox,
+ ),
+ hexdec(b'6EE84586DD2BCA0CAD3616940E164242'),
+ )
+ self.assertEqual(
+ cfb_decrypt(
+ key,
+ hexdec(b'6EE84586DD2BCA0CAD3616940E164242'),
+ iv=hexdec(b'0102030405060708'),
+ sbox=sbox,
+ ),
+ hexdec(b'112233445566778899AABBCCDD800000'),
+ )
+
+ def test_steps(self):
+ """ Check step-by-step operation manually
+ """
+ key = urandom(32)
+ iv = urandom(8)
+ plaintext = urandom(20)
+ ciphertext = cfb_encrypt(key, plaintext, iv)
+
+ # First full block
+ step = encrypt(DEFAULT_SBOX, key, block2ns(iv))
+ step = strxor(plaintext[:8], ns2block(step))
+ self.assertEqual(step, ciphertext[:8])
+
+ # Second full block
+ step = encrypt(DEFAULT_SBOX, key, block2ns(step))
+ step = strxor(plaintext[8:16], ns2block(step))
+ self.assertEqual(step, ciphertext[8:16])
+
+ # Third non-full block
+ step = encrypt(DEFAULT_SBOX, key, block2ns(step))
+ step = strxor(plaintext[16:] + 4 * b'\x00', ns2block(step))
+ self.assertEqual(step[:4], ciphertext[16:])
+
+ def test_random(self):
+ """ Random data with various sizes
+ """
+ key = urandom(32)
+ iv = urandom(8)
+ for size in (5, 8, 16, 120):
+ pt = urandom(size)
+ self.assertEqual(
+ cfb_decrypt(key, cfb_encrypt(key, pt, iv), iv), pt,
+ )
+
+
+class CTRTest(TestCase):
+ def test_gcl(self):
+ """ Test vectors from libgcl3
+ """
+ sbox = "Gost2814789_TestParamSet"
+ key = hexdec(b'0475f6e05038fbfad2c7c390edb3ca3d1547124291ae1e8a2f79cd9ed2bcefbd')
+ plaintext = bytes(bytearray((
+ 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
+ 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
+ 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
+ 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18,
+ 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20,
+ 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28,
+ 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30,
+ 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38,
+ 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40,
+ 0x4f, 0x4e, 0x4d, 0x4c, 0x4b, 0x4a, 0x49, 0x48,
+ 0x57, 0x56, 0x55, 0x54, 0x53, 0x52, 0x51, 0x50,
+ 0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59, 0x58,
+ 0x67, 0x66, 0x65, 0x64, 0x63, 0x62, 0x61, 0x60,
+ 0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68,
+ 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70,
+ 0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a, 0x79, 0x78,
+ 0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80,
+ 0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88,
+ 0x97, 0x96, 0x95, 0x94, 0x93, 0x92, 0x91, 0x90,
+ 0x9f, 0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98,
+ 0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1, 0xa0,
+ 0xaf, 0xae, 0xad, 0xac, 0xab, 0xaa, 0xa9, 0xa8,
+ 0xb7, 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0,
+ 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8,
+ 0xc7, 0xc6, 0xc5, 0xc4, 0xc3, 0xc2, 0xc1, 0xc0,
+ 0xcf, 0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8,
+ 0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1, 0xd0,
+ 0xdf, 0xde, 0xdd, 0xdc, 0xdb, 0xda, 0xd9, 0xd8,
+ 0xe7, 0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0,
+ 0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9, 0xe8,
+ 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0,
+ 0xff, 0xfe, 0xfd, 0xfc, 0xfb,
+ )))
+ ciphertext = bytes(bytearray((
+ 0x4a, 0x5e, 0x37, 0x6c, 0xa1, 0x12, 0xd3, 0x55,
+ 0x09, 0x13, 0x1a, 0x21, 0xac, 0xfb, 0xb2, 0x1e,
+ 0x8c, 0x24, 0x9b, 0x57, 0x20, 0x68, 0x46, 0xd5,
+ 0x23, 0x2a, 0x26, 0x35, 0x12, 0x56, 0x5c, 0x69,
+ 0x2a, 0x2f, 0xd1, 0xab, 0xbd, 0x45, 0xdc, 0x3a,
+ 0x1a, 0xa4, 0x57, 0x64, 0xd5, 0xe4, 0x69, 0x6d,
+ 0xb4, 0x8b, 0xf1, 0x54, 0x78, 0x3b, 0x10, 0x8f,
+ 0x7a, 0x4b, 0x32, 0xe0, 0xe8, 0x4c, 0xbf, 0x03,
+ 0x24, 0x37, 0x95, 0x6a, 0x55, 0xa8, 0xce, 0x6f,
+ 0x95, 0x62, 0x12, 0xf6, 0x79, 0xe6, 0xf0, 0x1b,
+ 0x86, 0xef, 0x36, 0x36, 0x05, 0xd8, 0x6f, 0x10,
+ 0xa1, 0x41, 0x05, 0x07, 0xf8, 0xfa, 0xa4, 0x0b,
+ 0x17, 0x2c, 0x71, 0xbc, 0x8b, 0xcb, 0xcf, 0x3d,
+ 0x74, 0x18, 0x32, 0x0b, 0x1c, 0xd2, 0x9e, 0x75,
+ 0xba, 0x3e, 0x61, 0xe1, 0x61, 0x96, 0xd0, 0xee,
+ 0x8f, 0xf2, 0x9a, 0x5e, 0xb7, 0x7a, 0x15, 0xaa,
+ 0x4e, 0x1e, 0x77, 0x7c, 0x99, 0xe1, 0x41, 0x13,
+ 0xf4, 0x60, 0x39, 0x46, 0x4c, 0x35, 0xde, 0x95,
+ 0xcc, 0x4f, 0xd5, 0xaf, 0xd1, 0x4d, 0x84, 0x1a,
+ 0x45, 0xc7, 0x2a, 0xf2, 0x2c, 0xc0, 0xb7, 0x94,
+ 0xa3, 0x08, 0xb9, 0x12, 0x96, 0xb5, 0x97, 0x99,
+ 0x3a, 0xb7, 0x0c, 0x14, 0x56, 0xb9, 0xcb, 0x49,
+ 0x44, 0xa9, 0x93, 0xa9, 0xfb, 0x19, 0x10, 0x8c,
+ 0x6a, 0x68, 0xe8, 0x7b, 0x06, 0x57, 0xf0, 0xef,
+ 0x88, 0x44, 0xa6, 0xd2, 0x98, 0xbe, 0xd4, 0x07,
+ 0x41, 0x37, 0x45, 0xa6, 0x71, 0x36, 0x76, 0x69,
+ 0x4b, 0x75, 0x15, 0x33, 0x90, 0x29, 0x6e, 0x33,
+ 0xcb, 0x96, 0x39, 0x78, 0x19, 0x2e, 0x96, 0xf3,
+ 0x49, 0x4c, 0x89, 0x3d, 0xa1, 0x86, 0x82, 0x00,
+ 0xce, 0xbd, 0x54, 0x29, 0x65, 0x00, 0x1d, 0x16,
+ 0x13, 0xc3, 0xfe, 0x1f, 0x8c, 0x55, 0x63, 0x09,
+ 0x1f, 0xcd, 0xd4, 0x28, 0xca,
+ )))
+ iv = b'\x02\x01\x01\x01\x01\x01\x01\x01'
+ encrypted = cnt(key, plaintext, iv=iv, sbox=sbox)
+ self.assertEqual(encrypted, ciphertext)
+ decrypted = cnt(key, encrypted, iv=iv, sbox=sbox)
+ self.assertEqual(decrypted, plaintext)
+
+ def test_gcl2(self):
+ """ Test vectors 2 from libgcl3
+ """
+ sbox = "Gost2814789_TestParamSet"
+ key = hexdec(b'fc7ad2886f455b50d29008fa622b57d5c65b3c637202025799cadf0768519e8a')
+ plaintext = bytes(bytearray((
+ 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
+ 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
+ 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
+ 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18,
+ 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20,
+ 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28,
+ 0xff, 0xfe, 0xfd, 0xfc, 0xfb,
+ )))
+ ciphertext = bytes(bytearray((
+ 0xd0, 0xbe, 0x60, 0x1a, 0x2c, 0xf1, 0x90, 0x26,
+ 0x9b, 0x7b, 0x23, 0xb4, 0xd2, 0xcc, 0xe1, 0x15,
+ 0xf6, 0x05, 0x57, 0x28, 0x88, 0x75, 0xeb, 0x1e,
+ 0xd3, 0x62, 0xdc, 0xda, 0x9b, 0x62, 0xee, 0x9a,
+ 0x57, 0x87, 0x8a, 0xf1, 0x82, 0x37, 0x9c, 0x7f,
+ 0x13, 0xcc, 0x55, 0x38, 0xb5, 0x63, 0x32, 0xc5,
+ 0x23, 0xa4, 0xcb, 0x7d, 0x51,
+ )))
+ iv = 8 * b'\x00'
+ encrypted = cnt(key, plaintext, iv=iv, sbox=sbox)
+ self.assertEqual(encrypted, ciphertext)
+ decrypted = cnt(key, encrypted, iv=iv, sbox=sbox)
+ self.assertEqual(decrypted, plaintext)
+
+
+class CBCTest(TestCase):
+ def test_pad_requirement(self):
+ key = 32 * b'x'
+ for s in (b'', b'foo', b'foobarbaz'):
+ with self.assertRaises(ValueError):
+ cbc_encrypt(key, s, pad=False)
+ with self.assertRaises(ValueError):
+ cbc_decrypt(key, s, pad=False)
+
+ def test_passes(self):
+ iv = urandom(8)
+ key = 32 * b'x'
+ for pt in (b'foo', b'foobarba', b'foobarbaz', 16 * b'x'):
+ ct = cbc_encrypt(key, pt, iv)
+ dt = cbc_decrypt(key, ct)
+ self.assertEqual(pt, dt)
+
+ def test_iv_existence_check(self):
+ key = 32 * b'x'
+ with self.assertRaises(ValueError):
+ cbc_decrypt(key, 8 * b'x')
+ iv = urandom(8)
+ cbc_decrypt(key, cbc_encrypt(key, 8 * b'x', iv))
+
+
+class CFBMeshingTest(TestCase):
+ def setUp(self):
+ self.key = urandom(32)
+ self.iv = urandom(8)
+
+ def test_single(self):
+ pt = b'\x00'
+ ct = cfb_encrypt(self.key, pt, mesh=True)
+ dec = cfb_decrypt(self.key, ct, mesh=True)
+ self.assertEqual(pt, dec)
+
+ def test_short(self):
+ pt = urandom(MESH_MAX_DATA - 1)
+ ct = cfb_encrypt(self.key, pt, mesh=True)
+ dec = cfb_decrypt(self.key, ct, mesh=True)
+ dec_plain = cfb_decrypt(self.key, ct)
+ self.assertEqual(pt, dec)
+ self.assertEqual(pt, dec_plain)
+
+ def test_short_iv(self):
+ pt = urandom(MESH_MAX_DATA - 1)
+ ct = cfb_encrypt(self.key, pt, iv=self.iv, mesh=True)
+ dec = cfb_decrypt(self.key, ct, iv=self.iv, mesh=True)
+ dec_plain = cfb_decrypt(self.key, ct, iv=self.iv)
+ self.assertEqual(pt, dec)
+ self.assertEqual(pt, dec_plain)
+
+ def test_longer_iv(self):
+ pt = urandom(MESH_MAX_DATA * 3)
+ ct = cfb_encrypt(self.key, pt, iv=self.iv, mesh=True)
+ dec = cfb_decrypt(self.key, ct, iv=self.iv, mesh=True)
+ dec_plain = cfb_decrypt(self.key, ct, iv=self.iv)
+ self.assertEqual(pt, dec)
+ self.assertNotEqual(pt, dec_plain)
--- /dev/null
+# coding: utf-8
+# PyGOST -- Pure Python GOST cryptographic functions library
+# Copyright (C) 2015-2016 Sergey Matveev <stargrave@stargrave.org>
+#
+# 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 <http://www.gnu.org/licenses/>.
+
+from unittest import TestCase
+
+from pygost.gost28147_mac import MAC
+
+
+class TestMAC(TestCase):
+ """ Test vectors generated with libgcl3 library
+ """
+ k = b'This is message\xFF length\x0032 bytes'
+
+ def test_a(self):
+ self.assertEqual(
+ MAC(self.k, b'a').hexdigest(),
+ 'bd5d3b5b2b7b57af',
+ )
+
+ def test_abc(self):
+ self.assertEqual(
+ MAC(self.k, b'abc').hexdigest(),
+ '28661e40805b1ff9',
+ )
+
+ def test_128U(self):
+ self.assertEqual(
+ MAC(self.k, 128 * b'U').hexdigest(),
+ '1a06d1bad74580ef',
+ )
+
+ def test_13x(self):
+ self.assertEqual(
+ MAC(self.k, 13 * b'x').hexdigest(),
+ '917ee1f1a668fbd3',
+ )
+
+ def test_parts(self):
+ m = MAC(self.k)
+ m.update(b'foo')
+ m.update(b'bar')
+ self.assertEqual(m.digest(), MAC(self.k, b'foobar').digest())
+
+ def test_copy(self):
+ m = MAC(self.k, b'foo')
+ c = m.copy()
+ m.update(b'barbaz')
+ c.update(b'bar')
+ c.update(b'baz')
+ self.assertEqual(m.digest(), c.digest())
--- /dev/null
+# coding: utf-8
+# PyGOST -- Pure Python GOST cryptographic functions library
+# Copyright (C) 2015-2016 Sergey Matveev <stargrave@stargrave.org>
+#
+# 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 <http://www.gnu.org/licenses/>.
+
+from os import urandom
+from unittest import TestCase
+
+from pygost.gost3410 import CURVE_PARAMS
+from pygost.gost3410 import GOST3410Curve
+from pygost.gost3410 import kek
+from pygost.gost3410 import public_key
+from pygost.gost3410 import sign
+from pygost.gost3410 import SIZE_3410_2001
+from pygost.gost3410 import SIZE_3410_2012
+from pygost.gost3410 import verify
+from pygost.utils import bytes2long
+from pygost.utils import long2bytes
+
+
+class Test341001(TestCase):
+ def test_rfc(self):
+ """ Test vector from :rfc:`5832`
+ """
+ private_key = bytes(bytearray((
+ 0x7A, 0x92, 0x9A, 0xDE, 0x78, 0x9B, 0xB9, 0xBE,
+ 0x10, 0xED, 0x35, 0x9D, 0xD3, 0x9A, 0x72, 0xC1,
+ 0x1B, 0x60, 0x96, 0x1F, 0x49, 0x39, 0x7E, 0xEE,
+ 0x1D, 0x19, 0xCE, 0x98, 0x91, 0xEC, 0x3B, 0x28
+ )))
+ public_key_x = bytes(bytearray((
+ 0x7F, 0x2B, 0x49, 0xE2, 0x70, 0xDB, 0x6D, 0x90,
+ 0xD8, 0x59, 0x5B, 0xEC, 0x45, 0x8B, 0x50, 0xC5,
+ 0x85, 0x85, 0xBA, 0x1D, 0x4E, 0x9B, 0x78, 0x8F,
+ 0x66, 0x89, 0xDB, 0xD8, 0xE5, 0x6F, 0xD8, 0x0B
+ )))
+ public_key_y = bytes(bytearray((
+ 0x26, 0xF1, 0xB4, 0x89, 0xD6, 0x70, 0x1D, 0xD1,
+ 0x85, 0xC8, 0x41, 0x3A, 0x97, 0x7B, 0x3C, 0xBB,
+ 0xAF, 0x64, 0xD1, 0xC5, 0x93, 0xD2, 0x66, 0x27,
+ 0xDF, 0xFB, 0x10, 0x1A, 0x87, 0xFF, 0x77, 0xDA
+ )))
+ digest = bytes(bytearray((
+ 0x2D, 0xFB, 0xC1, 0xB3, 0x72, 0xD8, 0x9A, 0x11,
+ 0x88, 0xC0, 0x9C, 0x52, 0xE0, 0xEE, 0xC6, 0x1F,
+ 0xCE, 0x52, 0x03, 0x2A, 0xB1, 0x02, 0x2E, 0x8E,
+ 0x67, 0xEC, 0xE6, 0x67, 0x2B, 0x04, 0x3E, 0xE5
+ )))
+ signature = bytes(bytearray((
+ 0x41, 0xAA, 0x28, 0xD2, 0xF1, 0xAB, 0x14, 0x82,
+ 0x80, 0xCD, 0x9E, 0xD5, 0x6F, 0xED, 0xA4, 0x19,
+ 0x74, 0x05, 0x35, 0x54, 0xA4, 0x27, 0x67, 0xB8,
+ 0x3A, 0xD0, 0x43, 0xFD, 0x39, 0xDC, 0x04, 0x93,
+ 0x01, 0x45, 0x6C, 0x64, 0xBA, 0x46, 0x42, 0xA1,
+ 0x65, 0x3C, 0x23, 0x5A, 0x98, 0xA6, 0x02, 0x49,
+ 0xBC, 0xD6, 0xD3, 0xF7, 0x46, 0xB6, 0x31, 0xDF,
+ 0x92, 0x80, 0x14, 0xF6, 0xC5, 0xBF, 0x9C, 0x40
+ )))
+ private_key = bytes2long(private_key)
+ signature = signature[32:] + signature[:32]
+
+ c = GOST3410Curve(*CURVE_PARAMS["GostR3410_2001_TestParamSet"])
+ pubX, pubY = public_key(c, private_key)
+ self.assertEqual(long2bytes(pubX), public_key_x)
+ self.assertEqual(long2bytes(pubY), public_key_y)
+ s = sign(c, private_key, digest)
+ self.assertTrue(verify(c, pubX, pubY, digest, s))
+ self.assertTrue(verify(c, pubX, pubY, digest, signature))
+
+ def test_sequence(self):
+ c = GOST3410Curve(*CURVE_PARAMS['GostR3410_2001_TestParamSet'])
+ private_key = bytes2long(urandom(32))
+ pubX, pubY = public_key(c, private_key)
+ for _ in range(20):
+ digest = urandom(32)
+ s = sign(c, private_key, digest, size=SIZE_3410_2001)
+ self.assertTrue(verify(c, pubX, pubY, digest, s, size=SIZE_3410_2001))
+
+
+class Test34102012(TestCase):
+ def test_gcl3(self):
+ """ Test vector from libgcl3
+ """
+ p = bytes(bytearray((
+ 0x45, 0x31, 0xAC, 0xD1, 0xFE, 0x00, 0x23, 0xC7,
+ 0x55, 0x0D, 0x26, 0x7B, 0x6B, 0x2F, 0xEE, 0x80,
+ 0x92, 0x2B, 0x14, 0xB2, 0xFF, 0xB9, 0x0F, 0x04,
+ 0xD4, 0xEB, 0x7C, 0x09, 0xB5, 0xD2, 0xD1, 0x5D,
+ 0xF1, 0xD8, 0x52, 0x74, 0x1A, 0xF4, 0x70, 0x4A,
+ 0x04, 0x58, 0x04, 0x7E, 0x80, 0xE4, 0x54, 0x6D,
+ 0x35, 0xB8, 0x33, 0x6F, 0xAC, 0x22, 0x4D, 0xD8,
+ 0x16, 0x64, 0xBB, 0xF5, 0x28, 0xBE, 0x63, 0x73
+ )))
+ q = bytes(bytearray((
+ 0x45, 0x31, 0xAC, 0xD1, 0xFE, 0x00, 0x23, 0xC7,
+ 0x55, 0x0D, 0x26, 0x7B, 0x6B, 0x2F, 0xEE, 0x80,
+ 0x92, 0x2B, 0x14, 0xB2, 0xFF, 0xB9, 0x0F, 0x04,
+ 0xD4, 0xEB, 0x7C, 0x09, 0xB5, 0xD2, 0xD1, 0x5D,
+ 0xA8, 0x2F, 0x2D, 0x7E, 0xCB, 0x1D, 0xBA, 0xC7,
+ 0x19, 0x90, 0x5C, 0x5E, 0xEC, 0xC4, 0x23, 0xF1,
+ 0xD8, 0x6E, 0x25, 0xED, 0xBE, 0x23, 0xC5, 0x95,
+ 0xD6, 0x44, 0xAA, 0xF1, 0x87, 0xE6, 0xE6, 0xDF
+ )))
+ a = bytes(bytearray((
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07
+ )))
+ b = bytes(bytearray((
+ 0x1C, 0xFF, 0x08, 0x06, 0xA3, 0x11, 0x16, 0xDA,
+ 0x29, 0xD8, 0xCF, 0xA5, 0x4E, 0x57, 0xEB, 0x74,
+ 0x8B, 0xC5, 0xF3, 0x77, 0xE4, 0x94, 0x00, 0xFD,
+ 0xD7, 0x88, 0xB6, 0x49, 0xEC, 0xA1, 0xAC, 0x43,
+ 0x61, 0x83, 0x40, 0x13, 0xB2, 0xAD, 0x73, 0x22,
+ 0x48, 0x0A, 0x89, 0xCA, 0x58, 0xE0, 0xCF, 0x74,
+ 0xBC, 0x9E, 0x54, 0x0C, 0x2A, 0xDD, 0x68, 0x97,
+ 0xFA, 0xD0, 0xA3, 0x08, 0x4F, 0x30, 0x2A, 0xDC
+ )))
+ x = bytes(bytearray((
+ 0x24, 0xD1, 0x9C, 0xC6, 0x45, 0x72, 0xEE, 0x30,
+ 0xF3, 0x96, 0xBF, 0x6E, 0xBB, 0xFD, 0x7A, 0x6C,
+ 0x52, 0x13, 0xB3, 0xB3, 0xD7, 0x05, 0x7C, 0xC8,
+ 0x25, 0xF9, 0x10, 0x93, 0xA6, 0x8C, 0xD7, 0x62,
+ 0xFD, 0x60, 0x61, 0x12, 0x62, 0xCD, 0x83, 0x8D,
+ 0xC6, 0xB6, 0x0A, 0xA7, 0xEE, 0xE8, 0x04, 0xE2,
+ 0x8B, 0xC8, 0x49, 0x97, 0x7F, 0xAC, 0x33, 0xB4,
+ 0xB5, 0x30, 0xF1, 0xB1, 0x20, 0x24, 0x8A, 0x9A
+ )))
+ y = bytes(bytearray((
+ 0x2B, 0xB3, 0x12, 0xA4, 0x3B, 0xD2, 0xCE, 0x6E,
+ 0x0D, 0x02, 0x06, 0x13, 0xC8, 0x57, 0xAC, 0xDD,
+ 0xCF, 0xBF, 0x06, 0x1E, 0x91, 0xE5, 0xF2, 0xC3,
+ 0xF3, 0x24, 0x47, 0xC2, 0x59, 0xF3, 0x9B, 0x2C,
+ 0x83, 0xAB, 0x15, 0x6D, 0x77, 0xF1, 0x49, 0x6B,
+ 0xF7, 0xEB, 0x33, 0x51, 0xE1, 0xEE, 0x4E, 0x43,
+ 0xDC, 0x1A, 0x18, 0xB9, 0x1B, 0x24, 0x64, 0x0B,
+ 0x6D, 0xBB, 0x92, 0xCB, 0x1A, 0xDD, 0x37, 0x1E
+ )))
+ private_key = bytes(bytearray((
+ 0x0B, 0xA6, 0x04, 0x8A, 0xAD, 0xAE, 0x24, 0x1B,
+ 0xA4, 0x09, 0x36, 0xD4, 0x77, 0x56, 0xD7, 0xC9,
+ 0x30, 0x91, 0xA0, 0xE8, 0x51, 0x46, 0x69, 0x70,
+ 0x0E, 0xE7, 0x50, 0x8E, 0x50, 0x8B, 0x10, 0x20,
+ 0x72, 0xE8, 0x12, 0x3B, 0x22, 0x00, 0xA0, 0x56,
+ 0x33, 0x22, 0xDA, 0xD2, 0x82, 0x7E, 0x27, 0x14,
+ 0xA2, 0x63, 0x6B, 0x7B, 0xFD, 0x18, 0xAA, 0xDF,
+ 0xC6, 0x29, 0x67, 0x82, 0x1F, 0xA1, 0x8D, 0xD4
+ )))
+ public_key_x = bytes(bytearray((
+ 0x11, 0x5D, 0xC5, 0xBC, 0x96, 0x76, 0x0C, 0x7B,
+ 0x48, 0x59, 0x8D, 0x8A, 0xB9, 0xE7, 0x40, 0xD4,
+ 0xC4, 0xA8, 0x5A, 0x65, 0xBE, 0x33, 0xC1, 0x81,
+ 0x5B, 0x5C, 0x32, 0x0C, 0x85, 0x46, 0x21, 0xDD,
+ 0x5A, 0x51, 0x58, 0x56, 0xD1, 0x33, 0x14, 0xAF,
+ 0x69, 0xBC, 0x5B, 0x92, 0x4C, 0x8B, 0x4D, 0xDF,
+ 0xF7, 0x5C, 0x45, 0x41, 0x5C, 0x1D, 0x9D, 0xD9,
+ 0xDD, 0x33, 0x61, 0x2C, 0xD5, 0x30, 0xEF, 0xE1
+ )))
+ public_key_y = bytes(bytearray((
+ 0x37, 0xC7, 0xC9, 0x0C, 0xD4, 0x0B, 0x0F, 0x56,
+ 0x21, 0xDC, 0x3A, 0xC1, 0xB7, 0x51, 0xCF, 0xA0,
+ 0xE2, 0x63, 0x4F, 0xA0, 0x50, 0x3B, 0x3D, 0x52,
+ 0x63, 0x9F, 0x5D, 0x7F, 0xB7, 0x2A, 0xFD, 0x61,
+ 0xEA, 0x19, 0x94, 0x41, 0xD9, 0x43, 0xFF, 0xE7,
+ 0xF0, 0xC7, 0x0A, 0x27, 0x59, 0xA3, 0xCD, 0xB8,
+ 0x4C, 0x11, 0x4E, 0x1F, 0x93, 0x39, 0xFD, 0xF2,
+ 0x7F, 0x35, 0xEC, 0xA9, 0x36, 0x77, 0xBE, 0xEC
+ )))
+ digest = bytes(bytearray((
+ 0x37, 0x54, 0xF3, 0xCF, 0xAC, 0xC9, 0xE0, 0x61,
+ 0x5C, 0x4F, 0x4A, 0x7C, 0x4D, 0x8D, 0xAB, 0x53,
+ 0x1B, 0x09, 0xB6, 0xF9, 0xC1, 0x70, 0xC5, 0x33,
+ 0xA7, 0x1D, 0x14, 0x70, 0x35, 0xB0, 0xC5, 0x91,
+ 0x71, 0x84, 0xEE, 0x53, 0x65, 0x93, 0xF4, 0x41,
+ 0x43, 0x39, 0x97, 0x6C, 0x64, 0x7C, 0x5D, 0x5A,
+ 0x40, 0x7A, 0xDE, 0xDB, 0x1D, 0x56, 0x0C, 0x4F,
+ 0xC6, 0x77, 0x7D, 0x29, 0x72, 0x07, 0x5B, 0x8C
+ )))
+ signature = bytes(bytearray((
+ 0x2F, 0x86, 0xFA, 0x60, 0xA0, 0x81, 0x09, 0x1A,
+ 0x23, 0xDD, 0x79, 0x5E, 0x1E, 0x3C, 0x68, 0x9E,
+ 0xE5, 0x12, 0xA3, 0xC8, 0x2E, 0xE0, 0xDC, 0xC2,
+ 0x64, 0x3C, 0x78, 0xEE, 0xA8, 0xFC, 0xAC, 0xD3,
+ 0x54, 0x92, 0x55, 0x84, 0x86, 0xB2, 0x0F, 0x1C,
+ 0x9E, 0xC1, 0x97, 0xC9, 0x06, 0x99, 0x85, 0x02,
+ 0x60, 0xC9, 0x3B, 0xCB, 0xCD, 0x9C, 0x5C, 0x33,
+ 0x17, 0xE1, 0x93, 0x44, 0xE1, 0x73, 0xAE, 0x36,
+ 0x10, 0x81, 0xB3, 0x94, 0x69, 0x6F, 0xFE, 0x8E,
+ 0x65, 0x85, 0xE7, 0xA9, 0x36, 0x2D, 0x26, 0xB6,
+ 0x32, 0x5F, 0x56, 0x77, 0x8A, 0xAD, 0xBC, 0x08,
+ 0x1C, 0x0B, 0xFB, 0xE9, 0x33, 0xD5, 0x2F, 0xF5,
+ 0x82, 0x3C, 0xE2, 0x88, 0xE8, 0xC4, 0xF3, 0x62,
+ 0x52, 0x60, 0x80, 0xDF, 0x7F, 0x70, 0xCE, 0x40,
+ 0x6A, 0x6E, 0xEB, 0x1F, 0x56, 0x91, 0x9C, 0xB9,
+ 0x2A, 0x98, 0x53, 0xBD, 0xE7, 0x3E, 0x5B, 0x4A
+ )))
+ private_key = bytes2long(private_key)
+ signature = signature[64:] + signature[:64]
+
+ c = GOST3410Curve(p, q, a, b, x, y)
+ pubX, pubY = public_key(c, private_key)
+ self.assertEqual(long2bytes(pubX), public_key_x)
+ self.assertEqual(long2bytes(pubY), public_key_y)
+ s = sign(c, private_key, digest, size=SIZE_3410_2012)
+ self.assertTrue(verify(c, pubX, pubY, digest, s, size=SIZE_3410_2012))
+ self.assertTrue(verify(c, pubX, pubY, digest, signature, size=SIZE_3410_2012))
+
+ def test_sequence(self):
+ c = GOST3410Curve(*CURVE_PARAMS['GostR3410_2012_TC26_ParamSetA'])
+ private_key = bytes2long(urandom(64))
+ pubX, pubY = public_key(c, private_key)
+ for _ in range(20):
+ digest = urandom(64)
+ s = sign(c, private_key, digest, size=SIZE_3410_2012)
+ self.assertTrue(verify(c, pubX, pubY, digest, s, size=SIZE_3410_2012))
+ self.assertNotIn(b'\x00' * 8, s)
+
+
+class TestVKO(TestCase):
+ def test_sequence(self):
+ curve = GOST3410Curve(*CURVE_PARAMS['GostR3410_2001_TestParamSet'])
+ for _ in range(20):
+ ukm = urandom(8)
+ prv1 = bytes2long(urandom(32))
+ prv2 = bytes2long(urandom(32))
+ pub1 = public_key(curve, prv1)
+ pub2 = public_key(curve, prv2)
+ kek1 = kek(curve, prv1, ukm, pub2)
+ kek2 = kek(curve, prv2, ukm, pub1)
+ self.assertEqual(kek1, kek2)
+ kek1 = kek(curve, prv1, ukm, pub1)
+ kek2 = kek(curve, prv2, ukm, pub2)
+ self.assertNotEqual(kek1, kek2)
--- /dev/null
+# coding: utf-8
+# PyGOST -- Pure Python GOST cryptographic functions library
+# Copyright (C) 2015-2016 Sergey Matveev <stargrave@stargrave.org>
+#
+# 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 <http://www.gnu.org/licenses/>.
+
+from unittest import TestCase
+import hmac
+
+from pygost import gost3411_2012
+from pygost.gost3411_2012 import GOST34112012
+from pygost.utils import hexdec
+
+
+class TestCopy(TestCase):
+ def runTest(self):
+ m = GOST34112012()
+ c = m.copy()
+ m.update(b'foobar')
+ c.update(b'foo')
+ c.update(b'bar')
+ self.assertEqual(m.digest(), c.digest())
+
+
+class TestHMACPEP247(TestCase):
+ def runTest(self):
+ h = hmac.new(b'foo', digestmod=gost3411_2012)
+ h.update(b'foobar')
+ h.digest()
+
+
+class TestVectors(TestCase):
+ def test_m1(self):
+ m = hexdec("323130393837363534333231303938373635343332313039383736353433323130393837363534333231303938373635343332313039383736353433323130")[::-1]
+ self.assertEqual(
+ GOST34112012(m).digest(),
+ hexdec("486f64c1917879417fef082b3381a4e211c324f074654c38823a7b76f830ad00fa1fbae42b1285c0352f227524bc9ab16254288dd6863dccd5b9f54a1ad0541b")[::-1]
+ )
+ self.assertEqual(
+ GOST34112012(m, digest_size=32).digest(),
+ hexdec("00557be5e584fd52a449b16b0251d05d27f94ab76cbaa6da890b59d8ef1e159d")[::-1]
+ )
+
+ def test_m2(self):
+ m = hexdec("fbe2e5f0eee3c820fbeafaebef20fffbf0e1e0f0f520e0ed20e8ece0ebe5f0f2f120fff0eeec20f120faf2fee5e2202ce8f6f3ede220e8e6eee1e8f0f2d1202ce8f0f2e5e220e5d1")[::-1]
+ self.assertEqual(
+ GOST34112012(m).digest(),
+ hexdec("28fbc9bada033b1460642bdcddb90c3fb3e56c497ccd0f62b8a2ad4935e85f037613966de4ee00531ae60f3b5a47f8dae06915d5f2f194996fcabf2622e6881e")[::-1]
+ )
+ self.assertEqual(
+ GOST34112012(m, digest_size=32).digest(),
+ hexdec("508f7e553c06501d749a66fc28c6cac0b005746d97537fa85d9e40904efed29d")[::-1]
+ )
+
+
+class TestTrivial(TestCase):
+ def not_failing(self):
+ GOST34112012(b'').digest()
+ GOST34112012(b'a').digest()
+ g = GOST34112012()
+ g = GOST34112012(g.digest_size * 'x')
+ g.digest()
+
+ def test_updates(self):
+ g = GOST34112012()
+ g.update(b'foo')
+ g.update(b'bar')
+ self.assertEqual(g.digest(), GOST34112012(b'foobar').digest())
--- /dev/null
+# coding: utf-8
+# PyGOST -- Pure Python GOST cryptographic functions library
+# Copyright (C) 2015-2016 Sergey Matveev <stargrave@stargrave.org>
+#
+# 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 <http://www.gnu.org/licenses/>.
+
+from unittest import TestCase
+import hmac
+
+from pygost import gost3411_94
+from pygost.gost3411_94 import GOST341194
+
+
+class TestCopy(TestCase):
+ def runTest(self):
+ m = GOST341194()
+ c = m.copy()
+ m.update(b'foobar')
+ c.update(b'foo')
+ c.update(b'bar')
+ self.assertEqual(m.digest(), c.digest())
+
+
+class TestHMACPEP247(TestCase):
+ def runTest(self):
+ h = hmac.new(b'foo', digestmod=gost3411_94)
+ h.update(b'foobar')
+ h.digest()
+
+
+class TestVectors(TestCase):
+ def test_empty(self):
+ self.assertEqual(
+ GOST341194(b'', "GostR3411_94_TestParamSet").hexdigest(),
+ "8d0f49492c91f45a68ff5c05d2c2b4ab78027b9aab5ce3feff5267c49cb985ce",
+ )
+
+ def test_a(self):
+ self.assertEqual(
+ GOST341194(b'a', "GostR3411_94_TestParamSet").hexdigest(),
+ "dd14f362cefd49f873a5c644431b87219c3449661f808ac8e9667c369e532cd4",
+ )
+
+ def test_abc(self):
+ self.assertEqual(
+ GOST341194(b'abc', "GostR3411_94_TestParamSet").hexdigest(),
+ "1dd5a4067c49703b75bc75c9290f5ecbb5eb85229e7277a2b2b14fc4484313f3",
+ )
+
+ def test_message_digest(self):
+ self.assertEqual(
+ GOST341194(b'message digest', "GostR3411_94_TestParamSet").hexdigest(),
+ "4d9a88a416de2fdb72de483f27652b5869243dec59be0cb6992c8fb1ec3444ad",
+ )
+
+ def test_Us(self):
+ self.assertEqual(
+ GOST341194(128 * b'U', "GostR3411_94_TestParamSet").hexdigest(),
+ "a43357fee8a926d9522a06870a66251c553e2774a0851d0cef0c1825eda3a353",
+ )
+
+ def test_dog(self):
+ self.assertEqual(
+ GOST341194(
+ b'The quick brown fox jumps over the lazy dog',
+ "GostR3411_94_TestParamSet",
+ ).hexdigest(),
+ "94421f6d370fa1d16ba7ac5e31296529c968047dca9bf4258ac59a0c41fab777",
+ )
+
+ def test_cog(self):
+ self.assertEqual(
+ GOST341194(
+ b'The quick brown fox jumps over the lazy cog',
+ "GostR3411_94_TestParamSet",
+ ).hexdigest(),
+ "45c4ee4ee1d25091312135540d6702e6677f7a73b5da31e10b8bb7aadac4eba3",
+ )
+
+ def test_rfc32(self):
+ self.assertEqual(
+ GOST341194(
+ b'This is message, length=32 bytes',
+ "GostR3411_94_TestParamSet",
+ ).hexdigest(),
+ "faff37a615a816691cff3ef8b68ca247e09525f39f8119832eb81975d366c4b1",
+ )
+
+ def test_rfc50(self):
+ self.assertEqual(
+ GOST341194(
+ b'Suppose the original message has length = 50 bytes',
+ "GostR3411_94_TestParamSet",
+ ).hexdigest(),
+ "0852f5623b89dd57aeb4781fe54df14eeafbc1350613763a0d770aa657ba1a47",
+ )
+
+
+class TestVectorsCryptoPro(TestCase):
+ """ CryptoPro S-box test vectors
+ """
+ def test_empty(self):
+ self.assertEqual(
+ GOST341194(b'', "GostR3411_94_CryptoProParamSet").hexdigest(),
+ "c056d64c2383c44a58139c9b560111ac133e43fb840f838714840ca33c5f1e98",
+ )
+
+ def test_a(self):
+ self.assertEqual(
+ GOST341194(b'a', "GostR3411_94_CryptoProParamSet").hexdigest(),
+ "1130402fcfaaf1ef3c13e3173f105a715580f7c97900af37bf832128dd524ce7",
+ )
+
+ def test_abc(self):
+ self.assertEqual(
+ GOST341194(b'abc', "GostR3411_94_CryptoProParamSet").hexdigest(),
+ "2cd42ff986293b167e994381ed59747414dd24953677762d39d718bf6d0585b2",
+ )
+
+ def test_message_digest(self):
+ self.assertEqual(
+ GOST341194(
+ b'message digest',
+ "GostR3411_94_CryptoProParamSet",
+ ).hexdigest(),
+ "a01b72299bc39a540fd672a99a72b4bdfe74417386986efaeb01a42add4160bc",
+ )
+
+ def test_dog(self):
+ self.assertEqual(
+ GOST341194(
+ b'The quick brown fox jumps over the lazy dog',
+ "GostR3411_94_CryptoProParamSet",
+ ).hexdigest(),
+ "760a8365d570476e787254761be7656774021b1f3de56f588c501a364a290490",
+ )
+
+ def test_32(self):
+ self.assertEqual(
+ GOST341194(
+ b'This is message, length=32 bytes',
+ "GostR3411_94_CryptoProParamSet",
+ ).hexdigest(),
+ "eb48de3e89e71bcb695fc752d617fae757f34fa77fa58ee114c5bdb7f7c2ef2c",
+ )
+
+ def test_50(self):
+ self.assertEqual(
+ GOST341194(
+ b'Suppose the original message has length = 50 bytes',
+ "GostR3411_94_CryptoProParamSet",
+ ).hexdigest(),
+ "1150a63031dc611a5f5e40d93153f74ebde8216f6792c25a91cfcabc5c0c73c3",
+ )
+
+ def test_Us(self):
+ self.assertEqual(
+ GOST341194(128 * b'U', "GostR3411_94_CryptoProParamSet").hexdigest(),
+ "e8c449f608104c512710cd37fded920df1e86b211623fa27f4bb914661c74a1c",
+ )
--- /dev/null
+# coding: utf-8
+# PyGOST -- Pure Python GOST cryptographic functions library
+# Copyright (C) 2015-2016 Sergey Matveev <stargrave@stargrave.org>
+#
+# 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 <http://www.gnu.org/licenses/>.
+
+from unittest import TestCase
+
+from pygost.gost3412 import C
+from pygost.gost3412 import GOST3412Kuz
+from pygost.gost3412 import L
+from pygost.gost3412 import PI
+from pygost.utils import hexdec
+
+
+def S(blk):
+ return bytearray(PI[v] for v in blk)
+
+
+def R(blk):
+ return L(blk, rounds=1)
+
+
+class STest(TestCase):
+ def test_vec1(self):
+ blk = bytearray(hexdec("ffeeddccbbaa99881122334455667700"))
+ self.assertEqual(S(blk), hexdec("b66cd8887d38e8d77765aeea0c9a7efc"))
+
+ def test_vec2(self):
+ blk = bytearray(hexdec("b66cd8887d38e8d77765aeea0c9a7efc"))
+ self.assertEqual(S(blk), hexdec("559d8dd7bd06cbfe7e7b262523280d39"))
+
+ def test_vec3(self):
+ blk = bytearray(hexdec("559d8dd7bd06cbfe7e7b262523280d39"))
+ self.assertEqual(S(blk), hexdec("0c3322fed531e4630d80ef5c5a81c50b"))
+
+ def test_vec4(self):
+ blk = bytearray(hexdec("0c3322fed531e4630d80ef5c5a81c50b"))
+ self.assertEqual(S(blk), hexdec("23ae65633f842d29c5df529c13f5acda"))
+
+
+class RTest(TestCase):
+ def test_vec1(self):
+ blk = bytearray(hexdec("00000000000000000000000000000100"))
+ self.assertEqual(R(blk), hexdec("94000000000000000000000000000001"))
+
+ def test_vec2(self):
+ blk = bytearray(hexdec("94000000000000000000000000000001"))
+ self.assertEqual(R(blk), hexdec("a5940000000000000000000000000000"))
+
+ def test_vec3(self):
+ blk = bytearray(hexdec("a5940000000000000000000000000000"))
+ self.assertEqual(R(blk), hexdec("64a59400000000000000000000000000"))
+
+ def test_vec4(self):
+ blk = bytearray(hexdec("64a59400000000000000000000000000"))
+ self.assertEqual(R(blk), hexdec("0d64a594000000000000000000000000"))
+
+
+class LTest(TestCase):
+ def test_vec1(self):
+ blk = bytearray(hexdec("64a59400000000000000000000000000"))
+ self.assertEqual(L(blk), hexdec("d456584dd0e3e84cc3166e4b7fa2890d"))
+
+ def test_vec2(self):
+ blk = bytearray(hexdec("d456584dd0e3e84cc3166e4b7fa2890d"))
+ self.assertEqual(L(blk), hexdec("79d26221b87b584cd42fbc4ffea5de9a"))
+
+ def test_vec3(self):
+ blk = bytearray(hexdec("79d26221b87b584cd42fbc4ffea5de9a"))
+ self.assertEqual(L(blk), hexdec("0e93691a0cfc60408b7b68f66b513c13"))
+
+ def test_vec4(self):
+ blk = bytearray(hexdec("0e93691a0cfc60408b7b68f66b513c13"))
+ self.assertEqual(L(blk), hexdec("e6a8094fee0aa204fd97bcb0b44b8580"))
+
+
+class KuznechikTest(TestCase):
+ key = hexdec("8899aabbccddeeff0011223344556677fedcba98765432100123456789abcdef")
+ plaintext = hexdec("1122334455667700ffeeddccbbaa9988")
+ ciphertext = hexdec("7f679d90bebc24305a468d42b9d4edcd")
+
+ def test_c(self):
+ self.assertEqual(C[0], hexdec("6ea276726c487ab85d27bd10dd849401"))
+ self.assertEqual(C[1], hexdec("dc87ece4d890f4b3ba4eb92079cbeb02"))
+ self.assertEqual(C[2], hexdec("b2259a96b4d88e0be7690430a44f7f03"))
+ self.assertEqual(C[3], hexdec("7bcd1b0b73e32ba5b79cb140f2551504"))
+ self.assertEqual(C[4], hexdec("156f6d791fab511deabb0c502fd18105"))
+ self.assertEqual(C[5], hexdec("a74af7efab73df160dd208608b9efe06"))
+ self.assertEqual(C[6], hexdec("c9e8819dc73ba5ae50f5b570561a6a07"))
+ self.assertEqual(C[7], hexdec("f6593616e6055689adfba18027aa2a08"))
+
+ def test_roundkeys(self):
+ ciph = GOST3412Kuz(self.key)
+ self.assertEqual(ciph.ks[0], hexdec("8899aabbccddeeff0011223344556677"))
+ self.assertEqual(ciph.ks[1], hexdec("fedcba98765432100123456789abcdef"))
+ self.assertEqual(ciph.ks[2], hexdec("db31485315694343228d6aef8cc78c44"))
+ self.assertEqual(ciph.ks[3], hexdec("3d4553d8e9cfec6815ebadc40a9ffd04"))
+ self.assertEqual(ciph.ks[4], hexdec("57646468c44a5e28d3e59246f429f1ac"))
+ self.assertEqual(ciph.ks[5], hexdec("bd079435165c6432b532e82834da581b"))
+ self.assertEqual(ciph.ks[6], hexdec("51e640757e8745de705727265a0098b1"))
+ self.assertEqual(ciph.ks[7], hexdec("5a7925017b9fdd3ed72a91a22286f984"))
+ self.assertEqual(ciph.ks[8], hexdec("bb44e25378c73123a5f32f73cdb6e517"))
+ self.assertEqual(ciph.ks[9], hexdec("72e9dd7416bcf45b755dbaa88e4a4043"))
+
+ def test_encrypt(self):
+ ciph = GOST3412Kuz(self.key)
+ self.assertEqual(ciph.encrypt(self.plaintext), self.ciphertext)
+
+ def test_decrypt(self):
+ ciph = GOST3412Kuz(self.key)
+ self.assertEqual(ciph.decrypt(self.ciphertext), self.plaintext)
--- /dev/null
+# coding: utf-8
+# PyGOST -- Pure Python GOST cryptographic functions library
+# Copyright (C) 2015-2016 Sergey Matveev <stargrave@stargrave.org>
+#
+# 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 <http://www.gnu.org/licenses/>.
+
+from os import urandom
+from unittest import TestCase
+
+from pygost.wrap import unwrap_cryptopro
+from pygost.wrap import unwrap_gost
+from pygost.wrap import wrap_cryptopro
+from pygost.wrap import wrap_gost
+
+
+class WrapGostTest(TestCase):
+ def test_symmetric(self):
+ for _ in range(1 << 8):
+ kek = urandom(32)
+ cek = urandom(32)
+ ukm = urandom(8)
+ wrapped = wrap_gost(ukm, kek, cek)
+ unwrapped = unwrap_gost(kek, wrapped)
+ self.assertEqual(unwrapped, cek)
+
+ def test_invalid_length(self):
+ with self.assertRaises(ValueError):
+ unwrap_gost(urandom(32), urandom(41))
+ with self.assertRaises(ValueError):
+ unwrap_gost(urandom(32), urandom(45))
+
+
+class WrapCryptoproTest(TestCase):
+ def test_symmetric(self):
+ for _ in range(1 << 8):
+ kek = urandom(32)
+ cek = urandom(32)
+ ukm = urandom(8)
+ wrapped = wrap_cryptopro(ukm, kek, cek)
+ unwrapped = unwrap_cryptopro(kek, wrapped)
+ self.assertEqual(unwrapped, cek)
--- /dev/null
+# coding: utf-8
+# PyGOST -- Pure Python GOST cryptographic functions library
+# Copyright (C) 2015-2016 Sergey Matveev <stargrave@stargrave.org>
+#
+# 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 <http://www.gnu.org/licenses/>.
+
+from os import urandom
+from unittest import TestCase
+
+from pygost.x509 import keypair_gen
+from pygost.x509 import sign
+from pygost.x509 import sign_digest
+from pygost.x509 import verify
+from pygost.x509 import verify_digest
+from pygost.x509 import SIZE_3410_2001
+from pygost.x509 import SIZE_3410_2012
+
+
+class X5092001Test(TestCase):
+ def test_symmetric(self):
+ for _ in range(1 << 4):
+ prv, pub = keypair_gen(urandom(SIZE_3410_2001), mode=2001)
+ digest = urandom(SIZE_3410_2001)
+ self.assertTrue(verify_digest(
+ pub, digest, sign_digest(prv, digest, mode=2001), mode=2001
+ ))
+ data = digest
+ self.assertTrue(verify(
+ pub, data, sign(prv, data, mode=2001), mode=2001
+ ))
+
+
+class X5092012Test(TestCase):
+ def test_symmetric(self):
+ for _ in range(1 << 4):
+ prv, pub = keypair_gen(urandom(SIZE_3410_2012), mode=2012)
+ digest = urandom(SIZE_3410_2012)
+ self.assertTrue(verify_digest(
+ pub, digest, sign_digest(prv, digest, mode=2012), mode=2012,
+ ))
+ data = digest
+ self.assertTrue(verify(
+ pub, data, sign(prv, data, mode=2012), mode=2012,
+ ))
--- /dev/null
+# coding: utf-8
+# PyGOST -- Pure Python GOST cryptographic functions library
+# Copyright (C) 2015-2016 Sergey Matveev <stargrave@stargrave.org>
+#
+# 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 <http://www.gnu.org/licenses/>.
+
+from codecs import getdecoder
+from codecs import getencoder
+from sys import version_info
+
+
+xrange = range if version_info[0] == 3 else xrange
+
+
+def strxor(a, b):
+ """ XOR of two strings
+
+ This function will process only shortest length of both strings,
+ ignoring remaining one.
+ """
+ mlen = min(len(a), len(b))
+ a, b, xor = bytearray(a), bytearray(b), bytearray(mlen)
+ for i in xrange(mlen):
+ xor[i] = a[i] ^ b[i]
+ return bytes(xor)
+
+
+_hexdecoder = getdecoder("hex")
+_hexencoder = getencoder("hex")
+
+
+def hexdec(data):
+ """Decode hexadecimal
+ """
+ return _hexdecoder(data)[0]
+
+
+def hexenc(data):
+ """Encode hexadecimal
+ """
+ return _hexencoder(data)[0].decode("ascii")
+
+
+def bytes2long(raw):
+ """ Deserialize big-endian bytes into long number
+
+ :param bytes raw: binary string
+ :return: deserialized long number
+ :rtype: int
+ """
+ return int(hexenc(raw), 16)
+
+
+def long2bytes(n, size=32):
+ """ Serialize long number into big-endian bytestring
+
+ :param long n: long number
+ :return: serialized bytestring
+ :rtype: bytes
+ """
+ res = hex(int(n))[2:].rstrip("L")
+ if len(res) % 2 != 0:
+ res = "0" + res
+ s = hexdec(res)
+ if len(s) != size:
+ s = (size - len(s)) * b'\x00' + s
+ return s
+
+
+def modinvert(a, n):
+ """ Modular multiplicative inverse
+
+ :return: inverse number. -1 if it does not exist
+
+ Realization is taken from:
+ https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
+ """
+ if a < 0:
+ # k^-1 = p - (-k)^-1 mod p
+ return n - modinvert(-a, n)
+ t, newt = 0, 1
+ r, newr = n, a
+ while newr != 0:
+ quotinent = r // newr
+ t, newt = newt, t - quotinent * newt
+ r, newr = newr, r - quotinent * newr
+ if r > 1:
+ return -1
+ if t < 0:
+ t = t + n
+ return t
--- /dev/null
+# coding: utf-8
+# PyGOST -- Pure Python GOST cryptographic functions library
+# Copyright (C) 2015-2016 Sergey Matveev <stargrave@stargrave.org>
+#
+# 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 <http://www.gnu.org/licenses/>.
+"""Key wrap.
+
+:rfc:`4357` key wrapping (28147-89 and CryptoPro).
+"""
+
+from struct import pack
+from struct import unpack
+
+from pygost.gost28147 import cfb_encrypt
+from pygost.gost28147 import ecb_decrypt
+from pygost.gost28147 import ecb_encrypt
+from pygost.gost28147_mac import MAC
+
+
+def wrap_gost(ukm, kek, cek):
+ """28147-89 key wrapping
+
+ :param ukm: UKM
+ :type ukm: bytes, 8 bytes
+ :param kek: key encryption key
+ :type kek: bytes, 32 bytes
+ :param cek: content encryption key
+ :type cek: bytes, 32 bytes
+ :return: wrapped key
+ :rtype: bytes, 44 bytes
+ """
+ cek_mac = MAC(kek, data=cek, iv=ukm).digest()[:4]
+ cek_enc = ecb_encrypt(kek, cek)
+ return ukm + cek_enc + cek_mac
+
+
+def unwrap_gost(kek, data):
+ """28147-89 key unwrapping
+
+ :param kek: key encryption key
+ :type kek: bytes, 32 bytes
+ :param data: wrapped key
+ :type data: bytes, 44 bytes
+ :return: unwrapped CEK
+ :rtype: 32 bytes
+ """
+ if len(data) != 44:
+ raise ValueError("Invalid data length")
+ ukm, cek_enc, cek_mac = data[:8], data[8:8 + 32], data[-4:]
+ cek = ecb_decrypt(kek, cek_enc)
+ if MAC(kek, data=cek, iv=ukm).digest()[:4] != cek_mac:
+ raise ValueError("Invalid MAC")
+ return cek
+
+
+def wrap_cryptopro(ukm, kek, cek):
+ """CryptoPro key wrapping
+
+ :param ukm: UKM
+ :type ukm: bytes, 8 bytes
+ :param kek: key encryption key
+ :type kek: bytes, 32 bytes
+ :param cek: content encryption key
+ :type cek: bytes, 32 bytes
+ :return: wrapped key
+ :rtype: bytes, 44 bytes
+ """
+ return wrap_gost(ukm, diversify(kek, bytearray(ukm)), cek)
+
+
+def unwrap_cryptopro(kek, data):
+ """CryptoPro key unwrapping
+
+ :param kek: key encryption key
+ :type kek: bytes, 32 bytes
+ :param data: wrapped key
+ :type data: bytes, 44 bytes
+ :return: unwrapped CEK
+ :rtype: 32 bytes
+ """
+ if len(data) < 8:
+ raise ValueError("Invalid data length")
+ return unwrap_gost(diversify(kek, bytearray(data[:8])), data)
+
+
+def diversify(kek, ukm):
+ out = kek
+ for i in range(8):
+ s1, s2 = 0, 0
+ for j in range(8):
+ k, = unpack("<i", out[j * 4:j * 4 + 4])
+ if (ukm[i] >> j) & 1:
+ s1 += k
+ else:
+ s2 += k
+ iv = pack("<I", s1 % 2 ** 32) + pack("<I", s2 % 2 ** 32)
+ out = cfb_encrypt(out, out, iv=iv)
+ return out
--- /dev/null
+# coding: utf-8
+# PyGOST -- Pure Python GOST cryptographic functions library
+# Copyright (C) 2015-2016 Sergey Matveev <stargrave@stargrave.org>
+#
+# 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 <http://www.gnu.org/licenses/>.
+""" :rfc:`4491` (using GOST algorithms with X.509) compatibility helpers
+
+Signature, public and private keys formats are defined in the RFC above.
+"""
+
+from pygost.gost3410 import CURVE_PARAMS
+from pygost.gost3410 import GOST3410Curve
+from pygost.gost3410 import public_key as _public_key
+from pygost.gost3410 import sign as _sign
+from pygost.gost3410 import SIZE_3410_2001
+from pygost.gost3410 import SIZE_3410_2012
+from pygost.gost3410 import verify as _verify
+from pygost.gost3411_2012 import GOST34112012
+from pygost.gost3411_94 import GOST341194
+from pygost.utils import bytes2long
+from pygost.utils import long2bytes
+
+
+GOST341194_SBOX = "GostR3411_94_CryptoProParamSet"
+MODE2PARAMS = {
+ 2001: "GostR3410_2001_CryptoPro_A_ParamSet",
+ 2012: "GostR3410_2012_TC26_ParamSetA",
+}
+MODE2SIZE = {
+ 2001: SIZE_3410_2001,
+ 2012: SIZE_3410_2012,
+}
+MODE2DIGEST = {
+ 2001: lambda data: GOST341194(data, sbox=GOST341194_SBOX).digest(),
+ 2012: lambda data: GOST34112012(data).digest(),
+}
+
+
+def keypair_gen(seed, mode=2001, curve_params=None):
+ """ Generate keypair
+
+ :param bytes seed: random data used as an entropy source
+ :param int mode: either 2001 or 2012
+ :param str curve_params: :py:data:`gost3410.CURVE_PARAMS` key identifying
+ curve parameters. GostR3410_2001_CryptoPro_A_ParamSet
+ will be used by default for 2001 mode and
+ GostR3410_2012_TC26_ParamSetA for 2012 one.
+ :return: private and public keys
+ :rtype: (bytes, bytes), 32/64 and 64/128 bytes
+ """
+ if len(seed) != MODE2SIZE[mode]:
+ raise ValueError("Invalid seed size")
+ curve_params = curve_params or MODE2PARAMS[mode]
+ curve = GOST3410Curve(*CURVE_PARAMS[curve_params])
+ private_key = seed
+ public_key_x, public_key_y = _public_key(curve, bytes2long(private_key))
+ public_key = (long2bytes(public_key_y) + long2bytes(public_key_x))[::-1]
+ return private_key[::-1], public_key
+
+
+def sign_digest(private_key, digest, mode=2001, curve_params=None):
+ """ Sign digest
+
+ :param bytes private_key: private key to sign with
+ :param bytes digest: precalculated digest
+ :param int mode: either 2001 or 2012
+ :param str curve_params: :py:data:`gost3410.CURVE_PARAMS` key identifying
+ curve parameters. GostR3410_2001_CryptoPro_A_ParamSet
+ will be used by default for 2001 mode and
+ GostR3410_2012_TC26_ParamSetA for 2012 one.
+ :return: signature
+ :rtype: bytes, 64/128 bytes
+ """
+ curve_params = curve_params or MODE2PARAMS[mode]
+ curve = GOST3410Curve(*CURVE_PARAMS[curve_params])
+ return _sign(
+ curve,
+ bytes2long(private_key[::-1]),
+ digest,
+ size=MODE2SIZE[mode],
+ )
+
+
+def verify_digest(public_key, digest, signature, mode=2001, curve_params=None):
+ """ Verify signature of the digest
+
+ :param bytes public_key: public key to verify with
+ :param bytes digest: precalculated digest
+ :param bytes signature: signature
+ :param int mode: either 2001 or 2012
+ :param str curve_params: :py:data:`gost3410.CURVE_PARAMS` key identifying
+ curve parameters. GostR3410_2001_CryptoPro_A_ParamSet
+ will be used by default for 2001 mode and
+ GostR3410_2012_TC26_ParamSetA for 2012 one.
+ :rtype: bool
+ """
+ curve_params = curve_params or MODE2PARAMS[mode]
+ curve = GOST3410Curve(*CURVE_PARAMS[curve_params])
+ public_key = public_key[::-1]
+ size = MODE2SIZE[mode]
+ return _verify(
+ curve,
+ bytes2long(public_key[size:]),
+ bytes2long(public_key[:size]),
+ digest,
+ signature,
+ size=MODE2SIZE[mode],
+ )
+
+
+def sign(private_key, data, mode=2001, curve_params=None):
+ """ Calculate data's digest and sign it
+
+ :param bytes private_key: private key to sign with
+ :param bytes data: arbitrary data
+ :param int mode: either 2001 or 2012
+ :param str curve_params: :py:data:`gost3410.CURVE_PARAMS` key identifying
+ curve parameters. GostR3410_2001_CryptoPro_A_ParamSet
+ will be used by default for 2001 mode and
+ GostR3410_2012_TC26_ParamSetA for 2012 one.
+ :return: signature
+ :rtype: bytes, 64/128 bytes
+ """
+ return sign_digest(private_key, MODE2DIGEST[mode](data), mode, curve_params)
+
+
+def verify(public_key, data, signature, mode=2001, curve_params=None):
+ """ Verify signature of the digest
+
+ :param bytes public_key: public key to verify with
+ :param bytes digest: precalculated digest
+ :param bytes signature: signature
+ :param int mode: either 2001 or 2012
+ :param str curve_params: :py:data:`gost3410.CURVE_PARAMS` key identifying
+ curve parameters. GostR3410_2001_CryptoPro_A_ParamSet
+ will be used by default for 2001 mode and
+ GostR3410_2012_TC26_ParamSetA for 2012 one.
+ :rtype: bool
+ """
+ return verify_digest(
+ public_key,
+ MODE2DIGEST[mode](data),
+ signature,
+ mode,
+ curve_params,
+ )
--- /dev/null
+from setuptools import setup
+
+version = open("VERSION", "rb").read().strip().decode("ascii")
+
+setup(
+ name="pygost",
+ version=version,
+ description="Pure Python GOST cryptographic functions library",
+ author="Sergey Matveev",
+ author_email="stargrave@stargrave.org",
+ url="http://www.cypherpunks.ru/pygost/",
+ license="GPLv3+",
+ classifiers=[
+ "Development Status :: 5 - Production/Stable",
+ "Intended Audience :: Developers",
+ "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
+ "Natural Language :: English",
+ "Programming Language :: Python :: 2",
+ "Programming Language :: Python :: 3",
+ "Topic :: Security :: Cryptography",
+ "Topic :: Software Development :: Libraries :: Python Modules",
+ ],
+ packages=["pygost", "supplementary"],
+ package_dir={"supplementary": "."},
+ package_data={
+ "pygost": ["stubs/**/*.pyi"],
+ "supplementary": [
+ "AUTHORS",
+ "COPYING",
+ "INSTALL",
+ "NEWS",
+ "PUBKEY.asc",
+ "README",
+ "VERSION",
+ ],
+ },
+)
--- /dev/null
+all: pygost.html
+
+MAKEINFO ?= makeinfo
+
+pygost.html: www.texi
+ rm -f pygost.html/*.html
+ $(MAKEINFO) --html \
+ --set-customization-variable NO_CSS=1 \
+ --set-customization-variable SHOW_TITLE=0 \
+ --set-customization-variable DATE_IN_HEADER=1 \
+ --set-customization-variable TOP_NODE_UP_URL=index.html \
+ -o pygost.html www.texi
--- /dev/null
+\input texinfo
+@documentencoding UTF-8
+@settitle PyGOST
+
+@copying
+Copyright @copyright{} 2015-2016 @email{stargrave@@stargrave.org, Sergey Matveev}
+@end copying
+
+@node Top
+@top PyGOST
+
+PyGOST is pure Python 2.7/3.x GOST cryptographic functions library.
+GOST is GOvernment STandard of Russian Federation (and Soviet Union).
+It is
+@url{https://www.gnu.org/philosophy/pragmatic.html, copylefted}
+@url{https://www.gnu.org/philosophy/free-sw.html, free software}:
+licenced under @url{https://www.gnu.org/licenses/gpl-3.0.html, GPLv3+}.
+
+Currently supported algorithms are:
+
+@itemize
+@item GOST 28147-89 (@url{https://tools.ietf.org/html/rfc5830.html, RFC 5830})
+ block cipher with ECB, CNT (CTR), CFB, MAC,
+ CBC (@url{https://tools.ietf.org/html/rfc4357.html, RFC 4357})
+ modes of operation
+@item various 28147-89-related S-boxes included
+@item GOST R 34.11-94 hash function
+ (@url{https://tools.ietf.org/html/rfc5831.html, RFC 5831})
+@item GOST R 34.11-2012 Стрибог (Streebog) hash function
+ (@url{https://tools.ietf.org/html/rfc6986.html, RFC 6986})
+@item GOST R 34.10-2001
+ (@url{https://tools.ietf.org/html/rfc5832.html, RFC 5832})
+ public key signature function
+@item GOST R 34.10-2012
+ (@url{https://tools.ietf.org/html/rfc7091.html, RFC 7091})
+ public key signature function
+@item various 34.10 curve parameters included
+@item VKO 34.10-2001 Diffie-Hellman function
+ (@url{https://tools.ietf.org/html/rfc4357.html, RFC 4357})
+@item 28147-89 and CryptoPro key wrapping
+ (@url{https://tools.ietf.org/html/rfc4357.html, RFC 4357})
+@item 28147-89 CryptoPro key meshing for CFB mode
+ (@url{https://tools.ietf.org/html/rfc4357.html, RFC 4357})
+@item @url{https://tools.ietf.org/html/rfc4491.html, RFC 4491}
+ (using GOST algorithms with X.509) compatibility helpers
+@item GOST R 34.12-2015 128-bit block cipher Кузнечик (Kuznechik)
+ (@url{https://tools.ietf.org/html/rfc7801.html, RFC 7801})
+@item GOST R 34.13-2015 padding methods
+@item PEP247-compatible hash/MAC functions
+@end itemize
+
+Example X.509 compatible 34.10-2012 keypair generation, signing and
+verifying its signature:
+
+@verbatim
+>>> from pygost import x509
+>>> prv, pub = x509.keypair_gen(urandom(64), mode=2012)
+>>> data = b'some data'
+>>> signature = x509.sign(prv, data, mode=2012)
+>>> x509.verify(pub, data, signature, mode=2012)
+True
+@end verbatim
+
+Please send questions, bug reports and patches to
+@url{https://lists.cypherpunks.ru/mailman/listinfo/gost, gost}
+mailing list. Announcements also go to this mailing list.
+
+@insertcopying
+
+@node Download
+@unnumbered Download
+
+No additional dependencies except Python 2.7/3.x interpreter are required.
+
+Preferable way is to download tarball with the signature:
+
+@verbatim
+% wget http://www.cypherpunks.ru/pygost/pygost-2.3.tar.xz
+% wget http://www.cypherpunks.ru/pygost/pygost-2.3.tar.xz.sig
+% gpg --verify pygost-2.3.tar.xz.sig pygost-2.3.tar.xz
+% xz -d < pygost-2.3.tar.xz | tar xf -
+% cd pygost-2.3
+% python setup.py install
+@end verbatim
+
+@multitable {XXXXX} {XXXX KiB} {link sign} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
+@headitem Version @tab Size @tab Tarball @tab SHA256 checksum @tab Streebog-256 checksum
+
+@item 2.3 @tab 37 KiB
+@tab @url{pygost-2.3.tar.xz, link} @url{pygost-2.3.tar.xz.sig, sign}
+@tab @code{FF2C7E78 F3677B45 EB472DC6 1837C72C 0BD72387 AB0A9DC7 AD88AD11 59589732}
+@tab @code{42cfd0cdf357997a909a9114ca14391b4c5e8b62e298675f899b80a8a26d690f}
+
+@end multitable
+
+But also you can use PIP (@strong{no} authentication is performed!):
+
+@verbatim
+% pip install pygost==2.3
+@end verbatim
+
+You @strong{have to} verify downloaded tarballs integrity and
+authenticity to be sure that you retrieved trusted and untampered
+software. @url{https://www.gnupg.org/, The GNU Privacy Guard} is used
+for that purpose.
+
+For the very first time it it necessary to get signing public key and
+import it. It is provided below, but you should check alternative
+resources.
+
+@verbatim
+pub rsa2048/0xE6FD1269CD0C009E 2016-09-13
+ F55A 7619 3A0C 323A A031 0E6B E6FD 1269 CD0C 009E
+uid PyGOST releases <pygost at cypherpunks dot ru>
+@end verbatim
+
+@itemize
+
+@item @url{https://lists.cypherpunks.ru/mailman/listinfo/gost, gost} maillist
+
+@item
+@verbatim
+% gpg --keyserver hkp://keys.gnupg.net/ --recv-keys 0xE6FD1269CD0C009E
+% gpg --auto-key-locate dane --locate-keys pygost at cypherpunks dot ru
+% gpg --auto-key-locate wkd --locate-keys pygost at cypherpunks dot ru
+% gpg --auto-key-locate pka --locate-keys pygost at cypherpunks dot ru
+@end verbatim
+
+@item
+@verbatiminclude PUBKEY.asc
+
+@end itemize
+
+You can obtain development source code by cloning
+@url{http://git-scm.com/, Git}
+@url{https://git.cypherpunks.ru/cgit.cgi/pygost.git/, repository}.
+
+@bye