├── .appveyor.yml ├── .gitignore ├── .gitmodules ├── .travis.yml ├── COPYRIGHT ├── Cargo.toml ├── LICENSE-GPL ├── README.md ├── build.rs ├── src ├── encparams.rs ├── ffi.rs ├── lib.rs ├── rand.rs └── types.rs └── tests ├── key.rs ├── lib.rs └── poly.rs /.appveyor.yml: -------------------------------------------------------------------------------- 1 | environment: 2 | matrix: 3 | - TARGET: nightly-x86_64-pc-windows-gnu 4 | MSYS_BITS: 64 5 | - TARGET: nightly-i686-pc-windows-gnu 6 | MSYS_BITS: 32 7 | - TARGET: beta-x86_64-pc-windows-gnu 8 | MSYS_BITS: 64 9 | - TARGET: beta-i686-pc-windows-gnu 10 | MSYS_BITS: 32 11 | - TARGET: 1.13.0-x86_64-pc-windows-gnu 12 | MSYS_BITS: 64 13 | - TARGET: 1.13.0-i686-pc-windows-gnu 14 | MSYS_BITS: 32 15 | - TARGET: 1.13.0-x86_64-pc-windows-gnu 16 | MSYS_BITS: 64 17 | - TARGET: 1.13.0-i686-pc-windows-gnu 18 | MSYS_BITS: 32 19 | 20 | install: 21 | - git submodule update --init --recursive 22 | - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-${env:TARGET}.exe" -FileName "rust-install.exe" 23 | - ps: .\rust-install.exe /VERYSILENT /NORESTART /DIR="C:\rust" | Out-Null 24 | - ps: $env:PATH="$env:PATH;C:\rust\bin" 25 | - if defined MSYS_BITS set PATH=C:\msys64\mingw%MSYS_BITS%\bin;C:\msys64\usr\bin;%PATH% 26 | - del .\rust-install.exe 27 | - rustc -vV 28 | - cargo -vV 29 | 30 | build_script: 31 | - cargo build 32 | - cargo package 33 | 34 | test_script: 35 | - cargo test 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | src/*.bk 4 | tests/*.bk 5 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "src/c"] 2 | path = src/c 3 | url = https://github.com/tbuktu/libntru.git 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | cache: cargo 3 | dist: trusty 4 | sudo: false 5 | os: 6 | - linux 7 | - osx 8 | addons: 9 | apt: 10 | packages: 11 | - libcurl4-openssl-dev 12 | - libelf-dev 13 | - libdw-dev 14 | - binutils-dev 15 | 16 | # Run builds for all the supported trains 17 | rust: 18 | - nightly 19 | - beta 20 | - stable 21 | - 1.13.0 22 | 23 | # Load travis-cargo 24 | before_script: 25 | - | 26 | if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then 27 | pip install git+https://github.com/FractalGlobal/travis-cargo.git@fix-coveralls --user && 28 | export PATH=$HOME/.local/bin:$PATH 29 | fi 30 | 31 | # The main build 32 | script: 33 | - | 34 | if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then 35 | travis-cargo build && 36 | travis-cargo test && 37 | travis-cargo build -- --features "no-sse" && 38 | travis-cargo test -- --features "no-sse" && 39 | travis-cargo build -- --features "no-avx2" && 40 | travis-cargo test -- --features "no-avx2" && 41 | travis-cargo bench; 42 | fi 43 | - | 44 | if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then 45 | cargo build && 46 | cargo test && 47 | cargo build --features "no-sse" && 48 | cargo test --features "no-sse" && 49 | cargo build --features "no-avx2" && 50 | cargo test --features "no-avx2" && 51 | cargo bench; 52 | fi 53 | 54 | # Send coverage reports and upload docs 55 | after_success: 56 | - | 57 | if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then 58 | travis-cargo --only stable coveralls --no-sudo --verify; 59 | fi 60 | 61 | env: 62 | global: 63 | - TRAVIS_CARGO_NIGHTLY_FEATURE="" 64 | 65 | notifications: 66 | email: 67 | recipients: 68 | - matt@fractal.global 69 | - iban@fractal.global 70 | on_success: change 71 | on_failure: always 72 | -------------------------------------------------------------------------------- /COPYRIGHT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015, Iban Eguia 2 | Copyright (c) 2012, Tim Buktu 3 | Copyright (c) 2006, CRYPTOGAMS by 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions 8 | are met: 9 | 10 | * Redistributions of source code must retain copyright notices, 11 | this list of conditions and the following disclaimer. 12 | 13 | * Redistributions in binary form must reproduce the above 14 | copyright notice, this list of conditions and the following 15 | disclaimer in the documentation and/or other materials 16 | provided with the distribution. 17 | 18 | * Neither the name of the CRYPTOGAMS nor the names of its 19 | copyright holder and contributors may be used to endorse or 20 | promote products derived from this software without specific 21 | prior written permission. 22 | 23 | ALTERNATIVELY, provided that this notice is retained in full, this 24 | product may be distributed under the terms of the GNU General Public 25 | License (GPL), in which case the provisions of the GPL apply INSTEAD OF 26 | those given above. 27 | 28 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS 29 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 30 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 31 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 32 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 33 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 34 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 35 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 36 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 37 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 38 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 39 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ntru" 3 | version = "0.5.6" 4 | license = "GPL-3.0+/BSD-3-Clause" 5 | build = "build.rs" 6 | links = "ntru" 7 | readme = "README.md" 8 | repository = "https://github.com/FractalGlobal/ntru-rs" 9 | documentation = "https://docs.rs/ntru/" 10 | authors = ["Razican "] 11 | description = """ 12 | Implementation of the NTRUEncrypt algorithm. Interface to libntru. 13 | """ 14 | keywords = ["libntru", "NTRU", "NTRUEncrypt"] 15 | 16 | [features] 17 | default = [] 18 | no-sse = [] 19 | sse = [] 20 | no-avx2 = [] 21 | avx2 = [] 22 | 23 | [dependencies] 24 | libc = "^0.2" 25 | 26 | [build-dependencies] 27 | gcc = "^0.3" 28 | 29 | [dev-dependencies] 30 | rust-crypto = "^0.2" 31 | rand = "^0.3" 32 | -------------------------------------------------------------------------------- /LICENSE-GPL: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NTRUEncrypt library for Rust # 2 | 3 | [![Build Status](https://travis-ci.org/FractalGlobal/ntru-rs.svg?branch=master)](https://travis-ci.org/FractalGlobal/ntru-rs) 4 | [![Build status](https://ci.appveyor.com/api/projects/status/w352flnvc7psujnf?svg=true)](https://ci.appveyor.com/project/Razican/ntru-rs) 5 | [![Coverage Status](https://coveralls.io/repos/FractalGlobal/ntru-rs/badge.svg?branch=master&service=github)](https://coveralls.io/github/FractalGlobal/ntru-rs?branch=master) 6 | [![Crates.io](https://meritbadge.herokuapp.com/ntru)](https://crates.io/crates/ntru) 7 | 8 | This library implements an interface with 9 | *[libntru](https://tbuktu.github.io/ntru/)* C library. It is currently under 10 | development, but can be used to encrypt and decrypt data. The documentation can 11 | be found [here](http://fractal.global/ntru-rs). This library was selected due to 12 | its better performance comparing to the reference NTRUEncrypt implementation. 13 | 14 | # License # 15 | 16 | This program is free software: you can redistribute it and/or modify it under 17 | the terms of the GNU General Public License as published by the Free Software 18 | Foundation, either version 3 of the License, or (at your option) any later 19 | version. You can also redistribute it and/or modify it under the terms of the 20 | 3-clause BSD license, since this library is double licensed. 21 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | extern crate gcc; 2 | 3 | use std::fs::File; 4 | use std::path::Path; 5 | use std::io::Write; 6 | use std::process::Command; 7 | use std::env; 8 | 9 | fn main() { 10 | if cfg!(feature = "no-sse") && cfg!(feature = "sse") { 11 | panic!("You need to decide if you want SSE support or not. If you have doubts, simply disable both options and let the build script autodetect it."); 12 | } 13 | if cfg!(feature = "no-avx2") && cfg!(feature = "avx2") { 14 | panic!("You need to decide if you want AVX2 support or not. If you have doubts, simply disable both options and let the build script autodetect it."); 15 | } 16 | if cfg!(feature = "no-sse") && cfg!(feature = "avx2") { 17 | panic!("SSE is needed for AVX2 support."); 18 | } 19 | 20 | if cfg!(target_os = "linux") || cfg!(target_os = "macos") || cfg!(target_os = "windows") { 21 | env::set_var("CC", "gcc"); 22 | env::set_var("AS", "gcc -c"); 23 | if cfg!(target_os = "linux") { 24 | env::set_var("AR", "ar"); 25 | } 26 | } else if cfg!(target_os = "freebsd") || cfg!(target_os = "openbsd") { 27 | env::set_var("CC", "cc"); 28 | env::set_var("AS", "cc -c"); 29 | env::set_var("AR", "ar"); 30 | } 31 | 32 | let mut avx2 = if cfg!(feature = "no-avx2") { false } else if cfg!(target_os = "windows") { 33 | cfg!(feature = "avx2") 34 | } else { 35 | let output = if cfg!(target_os = "freebsd") || cfg!(target_os = "openbsd") { 36 | // /usr/bin/grep -o AVX2 /var/run/dmesg.boot | /usr/bin/head -1 37 | Command::new("/usr/bin/grep") 38 | .arg("-o") 39 | .arg("AVX2") 40 | .arg("/var/run/dmesg.boot") 41 | .output() 42 | .unwrap() 43 | } else if cfg!(target_os = "macos") { 44 | // /usr/sbin/sysctl machdep.cpu.features | grep -m 1 -ow AVX2 45 | Command::new("/usr/sbin/sysctl") 46 | .arg("machdep.cpu.features") 47 | .output() 48 | .unwrap() 49 | } else { 50 | // /bin/grep -m 1 -o avx2 /proc/cpuinfo 51 | Command::new("/bin/grep") 52 | .arg("-m") 53 | .arg("1") 54 | .arg("-o") 55 | .arg("avx2") 56 | .arg("/proc/cpuinfo") 57 | .output() 58 | .unwrap() 59 | }; 60 | 61 | let output = std::str::from_utf8(&output.stdout[..]).unwrap().trim(); 62 | 63 | if cfg!(target_os = "freebsd") || cfg!(target_os = "openbsd") || cfg!(target_os = "macos") { 64 | output.contains("AVX2") 65 | } else { 66 | output == "avx2" 67 | } 68 | }; 69 | 70 | let sse3 = if cfg!(feature = "no-sse3") { false } else if avx2 { true } else if cfg!(target_os = "windows") { 71 | cfg!(feature = "sse") 72 | } else { 73 | let output = if cfg!(target_os = "freebsd") || cfg!(target_os = "openbsd") { 74 | // /usr/bin/grep -o SSSE3 /var/run/dmesg.boot | /usr/bin/head -1 75 | Command::new("/usr/bin/grep") 76 | .arg("-o") 77 | .arg("SSE3") 78 | .arg("/var/run/dmesg.boot") 79 | .output() 80 | .unwrap() 81 | } else if cfg!(target_os = "macos") { 82 | // /usr/sbin/sysctl machdep.cpu.features | grep -m 1 -ow SSSE3 83 | Command::new("/usr/sbin/sysctl") 84 | .arg("machdep.cpu.features") 85 | .output() 86 | .unwrap() 87 | } else { 88 | // /bin/grep -m 1 -o ssse3 /proc/cpuinfo 89 | Command::new("/bin/grep") 90 | .arg("-m") 91 | .arg("1") 92 | .arg("-o") 93 | .arg("ssse3") 94 | .arg("/proc/cpuinfo") 95 | .output() 96 | .unwrap() 97 | }; 98 | let output = std::str::from_utf8(&output.stdout[..]).unwrap().trim(); 99 | 100 | if cfg!(target_os = "freebsd") || cfg!(target_os = "openbsd") || cfg!(target_os = "macos") { 101 | output.contains("SSSE3") 102 | } else { 103 | output == "ssse3" 104 | } 105 | }; 106 | 107 | if !sse3 { 108 | avx2 = false; 109 | } 110 | 111 | let mut cflags = "-g -Wall -Wextra -Wno-unused-parameter".to_owned(); 112 | if avx2 { 113 | cflags = cflags + " -mavx2"; 114 | } 115 | if sse3 { 116 | cflags = cflags + " -mssse3"; 117 | } else if cfg!(target_os = "macos") { 118 | cflags = cflags + " -march=x86-64"; 119 | } 120 | cflags = cflags + " -O2"; 121 | 122 | env::set_var("CFLAGS", cflags); 123 | 124 | let mut config = gcc::Config::new(); 125 | config.file("src/c/src/bitstring.c") 126 | .file("src/c/src/encparams.c") 127 | .file("src/c/src/hash.c") 128 | .file("src/c/src/idxgen.c") 129 | .file("src/c/src/key.c") 130 | .file("src/c/src/mgf.c") 131 | .file("src/c/src/ntru.c") 132 | .file("src/c/src/poly.c") 133 | .file("src/c/src/rand.c") 134 | .file("src/c/src/arith.c") 135 | .file("src/c/src/sha1.c") 136 | .file("src/c/src/sha2.c") 137 | .file("src/c/src/nist_ctr_drbg.c") 138 | .file("src/c/src/rijndael.c"); 139 | 140 | if sse3 && 141 | (cfg!(target_pointer_width = "64") || cfg!(target_os = "macos") || 142 | cfg!(target_os = "windows")) { 143 | let out = if cfg!(target_os = "windows") { 144 | Command::new("c:\\mingw\\msys\\1.0\\bin\\perl") 145 | .arg("src/c/src/sha1-mb-x86_64.pl") 146 | .arg("coff") 147 | .output() 148 | .unwrap() 149 | } else if cfg!(target_os = "macos") { 150 | Command::new("/usr/bin/perl") 151 | .arg("src/c/src/sha1-mb-x86_64.pl") 152 | .arg("macosx") 153 | .output() 154 | .unwrap() 155 | } else { 156 | Command::new("/usr/bin/perl") 157 | .arg("src/c/src/sha1-mb-x86_64.pl") 158 | .arg("elf") 159 | .output() 160 | .unwrap() 161 | }; 162 | let out = std::str::from_utf8(&out.stdout[..]).unwrap().trim(); 163 | 164 | let p = Path::new("src/c/src/sha1-mb-x86_64.s"); 165 | let mut f = File::create(&p).unwrap(); 166 | f.write(out.as_bytes()).unwrap(); 167 | 168 | Command::new(env::var("CC").unwrap()) 169 | .arg("-c") 170 | .arg("src/c/src/sha1-mb-x86_64.s") 171 | .arg("-o") 172 | .arg("src/c/src/sha1-mb-x86_64.o") 173 | .output() 174 | .unwrap(); 175 | 176 | let out = if cfg!(target_os = "windows") { 177 | Command::new("c:\\mingw\\msys\\1.0\\bin\\perl") 178 | .arg("src/c/src/sha256-mb-x86_64.pl") 179 | .arg("coff") 180 | .output() 181 | .unwrap() 182 | } else if cfg!(target_os = "macos") { 183 | Command::new("/usr/bin/perl") 184 | .arg("src/c/src/sha256-mb-x86_64.pl") 185 | .arg("macosx") 186 | .output() 187 | .unwrap() 188 | } else { 189 | Command::new("/usr/bin/perl") 190 | .arg("src/c/src/sha256-mb-x86_64.pl") 191 | .arg("elf") 192 | .output() 193 | .unwrap() 194 | }; 195 | let out = std::str::from_utf8(&out.stdout[..]).unwrap().trim(); 196 | 197 | let p = Path::new("src/c/src/sha256-mb-x86_64.s"); 198 | let mut f = File::create(&p).unwrap(); 199 | f.write(out.as_bytes()).unwrap(); 200 | 201 | Command::new(env::var("CC").unwrap()) 202 | .arg("-c") 203 | .arg("src/c/src/sha256-mb-x86_64.s") 204 | .arg("-o") 205 | .arg("src/c/src/sha256-mb-x86_64.o") 206 | .output() 207 | .unwrap(); 208 | 209 | config.object("src/c/src/sha1-mb-x86_64.o").object("src/c/src/sha256-mb-x86_64.o"); 210 | } 211 | 212 | config.include("src/c/src").compile("libntru.a"); 213 | 214 | if sse3 { 215 | println!("cargo:rustc-cfg=SSE3") 216 | } 217 | if avx2 { 218 | println!("cargo:rustc-cfg=AVX2") 219 | } 220 | } 221 | -------------------------------------------------------------------------------- /src/encparams.rs: -------------------------------------------------------------------------------- 1 | //! NTRU encryption parameters 2 | //! 3 | //! This module contains the parameters for NTRU encryption. Theese parameters must be used when 4 | //! encrypting, decrypting and generating key pairs. The recomendation is to use the default 5 | //! parameters for each level of security, and not use the deprecated parameters. The recommended 6 | //! parameters are the following: 7 | //! 8 | //! * `DEFAULT_PARAMS_112_BITS` for 112 bits of security. 9 | //! * `DEFAULT_PARAMS_128_BITS` for 128 bits of security. 10 | //! * `DEFAULT_PARAMS_192_BITS` for 192 bits of security. 11 | //! * `DEFAULT_PARAMS_256_BITS` for 256 bits of security. 12 | //! 13 | use libc::{c_char, uint16_t, uint8_t}; 14 | use std::fmt; 15 | use super::ffi; 16 | 17 | /// A set of parameters for NTRU encryption 18 | #[repr(C)] 19 | pub struct EncParams { 20 | /// Name of the parameter set 21 | name: [c_char; 11], 22 | /// Number of polynomial coefficients 23 | n: uint16_t, 24 | /// Modulus 25 | q: uint16_t, 26 | /// Product flag, 1 for product-form private keys, 0 for ternary 27 | prod_flag: uint8_t, 28 | /// Number of ones in the private polynomial f1 (if prod=1) or f (if prod=0) 29 | df1: uint16_t, 30 | /// Number of ones in the private polynomial f2; ignored if prod=0 31 | df2: uint16_t, 32 | /// Number of ones in the private polynomial f3; ignored if prod=0 33 | df3: uint16_t, 34 | /// Number of ones in the polynomial g (used during key generation) 35 | dg: uint16_t, 36 | /// Minimum acceptable number of -1's, 0's, and 1's in the polynomial m' in the last encryption 37 | /// step 38 | dm0: uint16_t, 39 | /// Number of random bits to prepend to the message 40 | db: uint16_t, 41 | /// A parameter for the Index Generation Function 42 | c: uint16_t, 43 | /// Minimum number of hash calls for the IGF to make 44 | min_calls_r: uint16_t, 45 | /// Minimum number of calls to generate the masking polynomial 46 | min_calls_mask: uint16_t, 47 | /// Whether to hash the seed in the MGF first (1) or use the seed directly (0) 48 | hash_seed: uint8_t, 49 | /// Three bytes that uniquely identify the parameter set 50 | oid: [uint8_t; 3], 51 | /// Hash function, e.g. ntru_sha256 52 | hash: unsafe extern "C" fn(input: *const uint8_t, 53 | input_len: uint16_t, 54 | digest: *mut uint8_t), 55 | /// Hash function for 4 inputs, e.g. ntru_sha256_4way 56 | hash_4way: unsafe extern "C" fn(input: *const *const uint8_t, 57 | input_len: uint16_t, 58 | digest: *mut *mut uint8_t), 59 | /// Hash function for 8 inputs, e.g. ntru_sha256_8way 60 | hash_8way: unsafe extern "C" fn(input: *const *const uint8_t, 61 | input_len: uint16_t, 62 | digest: *mut *mut uint8_t), 63 | /// output length of the hash function 64 | hlen: uint16_t, 65 | /// number of bits of the public key to hash 66 | pklen: uint16_t, 67 | } 68 | 69 | impl Default for EncParams { 70 | fn default() -> EncParams { 71 | EncParams { 72 | name: [0; 11], 73 | n: 0, 74 | q: 0, 75 | prod_flag: 0, 76 | df1: 0, 77 | df2: 0, 78 | df3: 0, 79 | dg: 0, 80 | dm0: 0, 81 | db: 0, 82 | c: 0, 83 | min_calls_r: 0, 84 | min_calls_mask: 0, 85 | hash_seed: 0, 86 | oid: [0; 3], 87 | hash: ffi::ntru_sha1, 88 | hash_4way: ffi::ntru_sha1_4way, 89 | hash_8way: ffi::ntru_sha1_8way, 90 | hlen: 0, 91 | pklen: 0, 92 | } 93 | } 94 | } 95 | 96 | impl PartialEq for EncParams { 97 | fn eq(&self, other: &EncParams) -> bool { 98 | self.name == other.name && self.n == other.n && self.q == other.q && 99 | self.prod_flag == other.prod_flag && self.df1 == other.df1 && 100 | (self.prod_flag == 0 || (self.df2 == other.df2 && self.df3 == other.df3)) && 101 | self.dm0 == other.dm0 && self.db == other.db && self.c == other.c && 102 | self.min_calls_r == other.min_calls_r && 103 | self.min_calls_mask == other.min_calls_mask && 104 | self.hash_seed == other.hash_seed && self.oid == other.oid && 105 | { 106 | let input = [0u8; 100]; 107 | let mut hash1 = [0u8; 256]; 108 | let mut hash2 = [0u8; 256]; 109 | unsafe { (self.hash)(&input[0], 100, &mut hash1[0]) }; 110 | unsafe { (other.hash)(&input[0], 100, &mut hash2[0]) }; 111 | 112 | for (i, b) in hash1.iter().enumerate() { 113 | if *b != hash2[i] { 114 | return false; 115 | } 116 | } 117 | true 118 | } && self.hlen == other.hlen && self.pklen == other.pklen 119 | } 120 | } 121 | 122 | 123 | impl fmt::Debug for EncParams { 124 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 125 | let mut name = String::with_capacity(10); 126 | for c in &self.name { 127 | name.push(*c as u8 as char); 128 | } 129 | write!(f, "param: {}", name) 130 | } 131 | } 132 | 133 | impl EncParams { 134 | /// Get the name of the parameter set 135 | pub fn get_name(&self) -> String { 136 | let slice: [u8; 11] = [self.name[0] as u8, 137 | self.name[1] as u8, 138 | self.name[2] as u8, 139 | self.name[3] as u8, 140 | self.name[4] as u8, 141 | self.name[5] as u8, 142 | self.name[6] as u8, 143 | self.name[7] as u8, 144 | self.name[8] as u8, 145 | self.name[9] as u8, 146 | self.name[10] as u8]; 147 | String::from_utf8_lossy(&slice).into_owned() 148 | } 149 | 150 | /// Get the number of polynomial coefficients 151 | pub fn get_n(&self) -> u16 { 152 | self.n 153 | } 154 | 155 | /// Get the modulus 156 | pub fn get_q(&self) -> u16 { 157 | self.q 158 | } 159 | 160 | /// Get the number of random bits to prepend to the message 161 | pub fn get_db(&self) -> u16 { 162 | self.db 163 | } 164 | 165 | /// Maximum message length 166 | pub fn max_msg_len(&self) -> u8 { 167 | (self.n / 2 * 3 / 8 - 1 - self.db / 8) as u8 168 | } 169 | 170 | /// Encryption length 171 | pub fn enc_len(&self) -> u16 { 172 | if self.q & (self.q - 1) != 0 { 173 | 0 174 | } else { 175 | let len_bits = self.n * EncParams::log2(self.q) as u16; 176 | (len_bits + 7) / 8 177 | } 178 | } 179 | 180 | /// Public key length 181 | pub fn public_len(&self) -> u16 { 182 | 4 + self.enc_len() 183 | } 184 | 185 | /// Private key length 186 | pub fn private_len(&self) -> u16 { 187 | let bits_per_idx = EncParams::log2(self.n - 1) as u16 + 1; 188 | if self.prod_flag == 1 { 189 | let poly1_len = 4 + (bits_per_idx * 2 * self.df1 + 7) / 8; 190 | let poly2_len = 4 + (bits_per_idx * 2 * self.df2 + 7) / 8; 191 | let poly3_len = 4 + (bits_per_idx * 2 * self.df3 + 7) / 8; 192 | 193 | 5 + poly1_len + poly2_len + poly3_len 194 | } else { 195 | 5 + 4 + (bits_per_idx * 2 * self.df1 + 7) / 8 196 | } 197 | } 198 | 199 | fn log2(n: u16) -> u8 { 200 | let mut n = n; 201 | let mut log = 0; 202 | while n > 1 { 203 | n /= 2; 204 | log += 1; 205 | } 206 | log 207 | } 208 | } 209 | 210 | /// An IEEE 1361.1 parameter set that gives 112 bits of security and is optimized for key size. 211 | pub const EES401EP1: EncParams = EncParams { 212 | name: [69, 69, 83, 52, 48, 49, 69, 80, 49, 0, 0], // EES401EP1 213 | n: 401, 214 | q: 2048, 215 | prod_flag: 0, 216 | df1: 113, 217 | df2: 0, 218 | df3: 0, 219 | dg: 133, 220 | dm0: 113, 221 | db: 112, 222 | c: 11, 223 | min_calls_r: 32, 224 | min_calls_mask: 9, 225 | hash_seed: 1, 226 | oid: [0, 2, 4], 227 | hash: ffi::ntru_sha1, 228 | hash_4way: ffi::ntru_sha1_4way, 229 | hash_8way: ffi::ntru_sha1_8way, 230 | hlen: 20, 231 | pklen: 114, 232 | }; 233 | 234 | /// An IEEE 1361.1 parameter set that gives 128 bits of security and is optimized for key size. 235 | pub const EES449EP1: EncParams = EncParams { 236 | name: [69, 69, 83, 52, 52, 57, 69, 80, 49, 0, 0], // EES449EP1 237 | n: 449, 238 | q: 2048, 239 | prod_flag: 0, 240 | df1: 134, 241 | df2: 0, 242 | df3: 0, 243 | dg: 149, 244 | dm0: 134, 245 | db: 128, 246 | c: 9, 247 | min_calls_r: 31, 248 | min_calls_mask: 9, 249 | hash_seed: 1, 250 | oid: [0, 3, 3], 251 | hash: ffi::ntru_sha1, 252 | hash_4way: ffi::ntru_sha1_4way, 253 | hash_8way: ffi::ntru_sha1_8way, 254 | hlen: 20, 255 | pklen: 128, 256 | }; 257 | 258 | /// An IEEE 1361.1 parameter set that gives 192 bits of security and is optimized for key size. 259 | pub const EES677EP1: EncParams = EncParams { 260 | name: [69, 69, 83, 54, 55, 55, 69, 80, 49, 0, 0], // EES677EP1 261 | n: 677, 262 | q: 2048, 263 | prod_flag: 0, 264 | df1: 157, 265 | df2: 0, 266 | df3: 0, 267 | dg: 225, 268 | dm0: 157, 269 | db: 192, 270 | c: 11, 271 | min_calls_r: 27, 272 | min_calls_mask: 9, 273 | hash_seed: 1, 274 | oid: [0, 5, 3], 275 | hash: ffi::ntru_sha256, 276 | hash_4way: ffi::ntru_sha256_4way, 277 | hash_8way: ffi::ntru_sha256_8way, 278 | hlen: 32, 279 | pklen: 192, 280 | }; 281 | 282 | /// An IEEE 1361.1 parameter set that gives 256 bits of security and is optimized for key size. 283 | pub const EES1087EP2: EncParams = EncParams { 284 | name: [69, 69, 83, 49, 48, 56, 55, 69, 80, 50, 0], // EES1087EP2 285 | n: 1087, 286 | q: 2048, 287 | prod_flag: 0, 288 | df1: 120, 289 | df2: 0, 290 | df3: 0, 291 | dg: 362, 292 | dm0: 120, 293 | db: 256, 294 | c: 13, 295 | min_calls_r: 25, 296 | min_calls_mask: 14, 297 | hash_seed: 1, 298 | oid: [0, 6, 3], 299 | hash: ffi::ntru_sha256, 300 | hash_4way: ffi::ntru_sha256_4way, 301 | hash_8way: ffi::ntru_sha256_8way, 302 | hlen: 32, 303 | pklen: 256, 304 | }; 305 | 306 | /// An IEEE 1361.1 parameter set that gives 112 bits of security and is a tradeoff between key size 307 | /// and encryption/decryption speed. 308 | pub const EES541EP1: EncParams = EncParams { 309 | name: [69, 69, 83, 53, 52, 49, 69, 80, 49, 0, 0], // EES541EP1 310 | n: 541, 311 | q: 2048, 312 | prod_flag: 0, 313 | df1: 49, 314 | df2: 0, 315 | df3: 0, 316 | dg: 180, 317 | dm0: 49, 318 | db: 112, 319 | c: 12, 320 | min_calls_r: 15, 321 | min_calls_mask: 11, 322 | hash_seed: 1, 323 | oid: [0, 2, 5], 324 | hash: ffi::ntru_sha1, 325 | hash_4way: ffi::ntru_sha1_4way, 326 | hash_8way: ffi::ntru_sha1_8way, 327 | hlen: 20, 328 | pklen: 112, 329 | }; 330 | 331 | /// An IEEE 1361.1 parameter set that gives 128 bits of security and is a tradeoff between key 332 | /// size and encryption/decryption speed. 333 | pub const EES613EP1: EncParams = EncParams { 334 | name: [69, 69, 83, 54, 49, 51, 69, 80, 49, 0, 0], // EES613EP1 335 | n: 613, 336 | q: 2048, 337 | prod_flag: 0, 338 | df1: 55, 339 | df2: 0, 340 | df3: 0, 341 | dg: 204, 342 | dm0: 55, 343 | db: 128, 344 | c: 11, 345 | min_calls_r: 16, 346 | min_calls_mask: 13, 347 | hash_seed: 1, 348 | oid: [0, 3, 4], 349 | hash: ffi::ntru_sha1, 350 | hash_4way: ffi::ntru_sha1_4way, 351 | hash_8way: ffi::ntru_sha1_8way, 352 | hlen: 20, 353 | pklen: 128, 354 | }; 355 | 356 | /// An IEEE 1361.1 parameter set that gives 192 bits of security and is a tradeoff between key size 357 | /// and encryption/decryption speed. 358 | pub const EES887EP1: EncParams = EncParams { 359 | name: [69, 69, 83, 56, 56, 55, 69, 80, 49, 0, 0], // EES887EP1 360 | n: 887, 361 | q: 2048, 362 | prod_flag: 0, 363 | df1: 81, 364 | df2: 0, 365 | df3: 0, 366 | dg: 295, 367 | dm0: 81, 368 | db: 192, 369 | c: 10, 370 | min_calls_r: 13, 371 | min_calls_mask: 12, 372 | hash_seed: 1, 373 | oid: [0, 5, 4], 374 | hash: ffi::ntru_sha256, 375 | hash_4way: ffi::ntru_sha256_4way, 376 | hash_8way: ffi::ntru_sha256_8way, 377 | hlen: 32, 378 | pklen: 192, 379 | }; 380 | 381 | /// An IEEE 1361.1 parameter set that gives 256 bits of security and is a tradeoff between key size 382 | /// and encryption/decryption speed. 383 | pub const EES1171EP1: EncParams = EncParams { 384 | name: [69, 69, 83, 49, 49, 55, 49, 69, 80, 49, 0], // EES1171EP1 385 | n: 1171, 386 | q: 2048, 387 | prod_flag: 0, 388 | df1: 106, 389 | df2: 0, 390 | df3: 0, 391 | dg: 390, 392 | dm0: 106, 393 | db: 256, 394 | c: 12, 395 | min_calls_r: 20, 396 | min_calls_mask: 15, 397 | hash_seed: 1, 398 | oid: [0, 6, 4], 399 | hash: ffi::ntru_sha256, 400 | hash_4way: ffi::ntru_sha256_4way, 401 | hash_8way: ffi::ntru_sha256_8way, 402 | hlen: 32, 403 | pklen: 256, 404 | }; 405 | 406 | /// An IEEE 1361.1 parameter set that gives 112 bits of security and is optimized for 407 | /// encryption/decryption speed. 408 | pub const EES659EP1: EncParams = EncParams { 409 | name: [69, 69, 83, 54, 53, 57, 69, 80, 49, 0, 0], // EES659EP1 410 | n: 659, 411 | q: 2048, 412 | prod_flag: 0, 413 | df1: 38, 414 | df2: 0, 415 | df3: 0, 416 | dg: 219, 417 | dm0: 38, 418 | db: 112, 419 | c: 11, 420 | min_calls_r: 11, 421 | min_calls_mask: 14, 422 | hash_seed: 1, 423 | oid: [0, 2, 6], 424 | hash: ffi::ntru_sha1, 425 | hash_4way: ffi::ntru_sha1_4way, 426 | hash_8way: ffi::ntru_sha1_8way, 427 | hlen: 20, 428 | pklen: 112, 429 | }; 430 | 431 | /// An IEEE 1361.1 parameter set that gives 128 bits of security and is optimized for 432 | /// encryption/decryption speed. 433 | pub const EES761EP1: EncParams = EncParams { 434 | name: [69, 69, 83, 55, 54, 49, 69, 80, 49, 0, 0], // EES761EP1 435 | n: 761, 436 | q: 2048, 437 | prod_flag: 0, 438 | df1: 42, 439 | df2: 0, 440 | df3: 0, 441 | dg: 253, 442 | dm0: 42, 443 | db: 128, 444 | c: 12, 445 | min_calls_r: 13, 446 | min_calls_mask: 16, 447 | hash_seed: 1, 448 | oid: [0, 3, 5], 449 | hash: ffi::ntru_sha1, 450 | hash_4way: ffi::ntru_sha1_4way, 451 | hash_8way: ffi::ntru_sha1_8way, 452 | hlen: 20, 453 | pklen: 128, 454 | }; 455 | 456 | /// An IEEE 1361.1 parameter set that gives 192 bits of security and is optimized for 457 | /// encryption/decryption speed. 458 | pub const EES1087EP1: EncParams = EncParams { 459 | name: [69, 69, 83, 49, 48, 56, 55, 69, 80, 49, 0], // EES1087EP1 460 | n: 1087, 461 | q: 2048, 462 | prod_flag: 0, 463 | df1: 63, 464 | df2: 0, 465 | df3: 0, 466 | dg: 362, 467 | dm0: 63, 468 | db: 192, 469 | c: 13, 470 | min_calls_r: 13, 471 | min_calls_mask: 14, 472 | hash_seed: 1, 473 | oid: [0, 5, 5], 474 | hash: ffi::ntru_sha256, 475 | hash_4way: ffi::ntru_sha256_4way, 476 | hash_8way: ffi::ntru_sha256_8way, 477 | hlen: 32, 478 | pklen: 192, 479 | }; 480 | 481 | /// An IEEE 1361.1 parameter set that gives 256 bits of security and is optimized for 482 | /// encryption/decryption speed. 483 | pub const EES1499EP1: EncParams = EncParams { 484 | name: [69, 69, 83, 49, 52, 57, 57, 69, 80, 49, 0], // EES1499EP1 485 | n: 1499, 486 | q: 2048, 487 | prod_flag: 0, 488 | df1: 79, 489 | df2: 0, 490 | df3: 0, 491 | dg: 499, 492 | dm0: 79, 493 | db: 256, 494 | c: 13, 495 | min_calls_r: 17, 496 | min_calls_mask: 19, 497 | hash_seed: 1, 498 | oid: [0, 6, 5], 499 | hash: ffi::ntru_sha256, 500 | hash_4way: ffi::ntru_sha256_4way, 501 | hash_8way: ffi::ntru_sha256_8way, 502 | hlen: 32, 503 | pklen: 256, 504 | }; 505 | 506 | /// A product-form parameter set that gives 112 bits of security. 507 | pub const EES401EP2: EncParams = EncParams { 508 | name: [69, 69, 83, 52, 48, 49, 69, 80, 50, 0, 0], // EES401EP2 509 | n: 401, 510 | q: 2048, 511 | prod_flag: 1, 512 | df1: 8, 513 | df2: 8, 514 | df3: 6, 515 | dg: 133, 516 | dm0: 101, 517 | db: 112, 518 | c: 11, 519 | min_calls_r: 10, 520 | min_calls_mask: 6, 521 | hash_seed: 1, 522 | oid: [0, 2, 16], 523 | hash: ffi::ntru_sha1, 524 | hash_4way: ffi::ntru_sha1_4way, 525 | hash_8way: ffi::ntru_sha1_8way, 526 | hlen: 20, 527 | pklen: 112, 528 | }; 529 | 530 | /// **DEPRECATED** A product-form parameter set that gives 128 bits of security. 531 | /// 532 | /// **Deprecated**, use EES443EP1 instead. 533 | pub const EES439EP1: EncParams = EncParams { 534 | name: [69, 69, 83, 52, 51, 57, 69, 80, 49, 0, 0], // EES439EP1 535 | n: 439, 536 | q: 2048, 537 | prod_flag: 1, 538 | df1: 9, 539 | df2: 8, 540 | df3: 5, 541 | dg: 146, 542 | dm0: 112, 543 | db: 128, 544 | c: 9, 545 | min_calls_r: 15, 546 | min_calls_mask: 6, 547 | hash_seed: 1, 548 | oid: [0, 3, 16], 549 | hash: ffi::ntru_sha1, 550 | hash_4way: ffi::ntru_sha1_4way, 551 | hash_8way: ffi::ntru_sha1_8way, 552 | hlen: 20, 553 | pklen: 128, 554 | }; 555 | 556 | /// A product-form parameter set that gives 128 bits of security. 557 | pub const EES443EP1: EncParams = EncParams { 558 | name: [69, 69, 83, 52, 52, 51, 69, 80, 49, 0, 0], 559 | n: 443, 560 | q: 2048, 561 | prod_flag: 1, 562 | df1: 9, 563 | df2: 8, 564 | df3: 5, 565 | dg: 148, 566 | dm0: 115, 567 | db: 128, 568 | c: 9, 569 | min_calls_r: 8, 570 | min_calls_mask: 5, 571 | hash_seed: 1, 572 | oid: [0, 3, 17], 573 | hash: ffi::ntru_sha256, 574 | hash_4way: ffi::ntru_sha256_4way, 575 | hash_8way: ffi::ntru_sha256_8way, 576 | hlen: 32, 577 | pklen: 128, 578 | }; 579 | 580 | /// **DEPRECATED** A product-form parameter set that gives 192 bits of security. 581 | /// 582 | /// **Deprecated**, use EES587EP1 instead. 583 | pub const EES593EP1: EncParams = EncParams { 584 | name: [69, 69, 83, 53, 57, 51, 69, 80, 49, 0, 0], // EES593EP1 585 | n: 593, 586 | q: 2048, 587 | prod_flag: 1, 588 | df1: 10, 589 | df2: 10, 590 | df3: 8, 591 | dg: 197, 592 | dm0: 158, 593 | db: 192, 594 | c: 11, 595 | min_calls_r: 12, 596 | min_calls_mask: 5, 597 | hash_seed: 1, 598 | oid: [0, 5, 16], 599 | hash: ffi::ntru_sha256, 600 | hash_4way: ffi::ntru_sha256_4way, 601 | hash_8way: ffi::ntru_sha256_8way, 602 | hlen: 32, 603 | pklen: 192, 604 | }; 605 | 606 | /// A product-form parameter set that gives 192 bits of security. 607 | pub const EES587EP1: EncParams = EncParams { 608 | name: [69, 69, 83, 53, 56, 55, 69, 80, 49, 0, 0], 609 | n: 587, 610 | q: 2048, 611 | prod_flag: 1, 612 | df1: 10, 613 | df2: 10, 614 | df3: 8, 615 | dg: 196, 616 | dm0: 157, 617 | db: 192, 618 | c: 11, 619 | min_calls_r: 13, 620 | min_calls_mask: 7, 621 | hash_seed: 1, 622 | oid: [0, 5, 17], 623 | hash: ffi::ntru_sha256, 624 | hash_4way: ffi::ntru_sha256_4way, 625 | hash_8way: ffi::ntru_sha256_8way, 626 | hlen: 32, 627 | pklen: 192, 628 | }; 629 | 630 | /// A product-form parameter set that gives 256 bits of security. 631 | pub const EES743EP1: EncParams = EncParams { 632 | name: [69, 69, 83, 55, 52, 51, 69, 80, 49, 0, 0], // EES743EP1 633 | n: 743, 634 | q: 2048, 635 | prod_flag: 1, 636 | df1: 11, 637 | df2: 11, 638 | df3: 15, 639 | dg: 247, 640 | dm0: 204, 641 | db: 256, 642 | c: 13, 643 | min_calls_r: 12, 644 | min_calls_mask: 7, 645 | hash_seed: 1, 646 | oid: [0, 6, 16], 647 | hash: ffi::ntru_sha256, 648 | hash_4way: ffi::ntru_sha256_4way, 649 | hash_8way: ffi::ntru_sha256_8way, 650 | hlen: 32, 651 | pklen: 256, 652 | }; 653 | 654 | /// The default parameter set for 112 bits of security. 655 | pub const DEFAULT_PARAMS_112_BITS: EncParams = EES541EP1; 656 | 657 | /// The default parameter set for 128 bits of security. 658 | pub const DEFAULT_PARAMS_128_BITS: EncParams = EES613EP1; 659 | 660 | /// The default parameter set for 192 bits of security. 661 | pub const DEFAULT_PARAMS_192_BITS: EncParams = EES887EP1; 662 | 663 | /// The default parameter set for 256 bits of security. 664 | pub const DEFAULT_PARAMS_256_BITS: EncParams = EES1171EP1; 665 | 666 | /// All parameter sets, in an array 667 | pub const ALL_PARAM_SETS: [EncParams; 18] = 668 | [EES401EP1, EES449EP1, EES677EP1, EES1087EP2, EES541EP1, EES613EP1, EES887EP1, EES1171EP1, 669 | EES659EP1, EES761EP1, EES1087EP1, EES1499EP1, EES401EP2, EES439EP1, EES443EP1, EES593EP1, 670 | EES587EP1, EES743EP1]; 671 | -------------------------------------------------------------------------------- /src/ffi.rs: -------------------------------------------------------------------------------- 1 | use libc::{uint16_t, int16_t, uint8_t}; 2 | 3 | use encparams::EncParams; 4 | use types::{IntPoly, ProdPoly, TernPoly, KeyPair, PrivPoly, PublicKey, PrivateKey}; 5 | use rand::{RandContext, RandGen}; 6 | 7 | extern "C" { 8 | // ntru.h 9 | pub fn ntru_gen_key_pair(params: *const EncParams, 10 | kp: *mut KeyPair, 11 | rand_ctx: *const RandContext) 12 | -> uint8_t; 13 | pub fn ntru_gen_key_pair_multi(params: *const EncParams, 14 | private: *mut PrivateKey, 15 | public: *mut PublicKey, 16 | rand_ctx: *const RandContext, 17 | num_pub: u32) 18 | -> uint8_t; 19 | pub fn ntru_gen_pub(params: *const EncParams, 20 | private: *const PrivateKey, 21 | public: *mut PublicKey, 22 | rand_ctx: *const RandContext) 23 | -> uint8_t; 24 | pub fn ntru_encrypt(msg: *const uint8_t, 25 | msg_len: uint16_t, 26 | public: *const PublicKey, 27 | params: *const EncParams, 28 | rand_ctx: *const RandContext, 29 | enc: *mut uint8_t) 30 | -> uint8_t; 31 | pub fn ntru_decrypt(enc: *const uint8_t, 32 | kp: *const KeyPair, 33 | params: *const EncParams, 34 | dec: *mut uint8_t, 35 | dec_len: *mut uint16_t) 36 | -> uint8_t; 37 | 38 | // hash.h 39 | pub fn ntru_sha1(input: *const uint8_t, input_len: uint16_t, digest: *mut uint8_t); 40 | pub fn ntru_sha1_4way(input: *const *const uint8_t, 41 | input_len: uint16_t, 42 | digest: *mut *mut uint8_t); 43 | pub fn ntru_sha1_8way(input: *const *const uint8_t, 44 | input_len: uint16_t, 45 | digest: *mut *mut uint8_t); 46 | pub fn ntru_sha256(input: *const uint8_t, input_len: uint16_t, digest: *mut uint8_t); 47 | pub fn ntru_sha256_4way(input: *const *const uint8_t, 48 | input_len: uint16_t, 49 | digest: *mut *mut uint8_t); 50 | pub fn ntru_sha256_8way(input: *const *const uint8_t, 51 | input_len: uint16_t, 52 | digest: *mut *mut uint8_t); 53 | 54 | // rand.h 55 | pub fn ntru_rand_init(rand_ctx: *mut RandContext, rand_gen: *const RandGen) -> uint8_t; 56 | pub fn ntru_rand_init_det(rand_ctx: *mut RandContext, 57 | rand_gen: *const RandGen, 58 | seed: *const uint8_t, 59 | seed_len: uint16_t) 60 | -> uint8_t; 61 | pub fn ntru_rand_generate(rand_data: *mut uint8_t, 62 | len: uint16_t, 63 | rand_ctx: *const RandContext) 64 | -> uint8_t; 65 | pub fn ntru_rand_release(rand_ctx: *mut RandContext) -> uint8_t; 66 | 67 | #[cfg(target_os = "windows")] 68 | pub fn ntru_rand_wincrypt_init(rand_ctx: *mut RandContext, 69 | rand_gen: *const RandGen) 70 | -> uint8_t; 71 | #[cfg(target_os = "windows")] 72 | pub fn ntru_rand_wincrypt_generate(rand_data: *mut uint8_t, 73 | len: uint16_t, 74 | rand_ctx: *const RandContext) 75 | -> uint8_t; 76 | #[cfg(target_os = "windows")] 77 | pub fn ntru_rand_wincrypt_release(rand_ctx: *mut RandContext) -> uint8_t; 78 | 79 | #[cfg(not(target_os = "windows"))] 80 | pub fn ntru_rand_devrandom_init(rand_ctx: *mut RandContext, 81 | rand_gen: *const RandGen) 82 | -> uint8_t; 83 | #[cfg(not(target_os = "windows"))] 84 | pub fn ntru_rand_devrandom_generate(rand_data: *mut uint8_t, 85 | len: uint16_t, 86 | rand_ctx: *const RandContext) 87 | -> uint8_t; 88 | #[cfg(not(target_os = "windows"))] 89 | pub fn ntru_rand_devrandom_release(rand_ctx: *mut RandContext) -> uint8_t; 90 | 91 | #[cfg(not(target_os = "windows"))] 92 | pub fn ntru_rand_devurandom_init(rand_ctx: *mut RandContext, 93 | rand_gen: *const RandGen) 94 | -> uint8_t; 95 | #[cfg(not(target_os = "windows"))] 96 | pub fn ntru_rand_devurandom_generate(rand_data: *mut uint8_t, 97 | len: uint16_t, 98 | rand_ctx: *const RandContext) 99 | -> uint8_t; 100 | #[cfg(not(target_os = "windows"))] 101 | pub fn ntru_rand_devurandom_release(rand_ctx: *mut RandContext) -> uint8_t; 102 | 103 | pub fn ntru_rand_default_init(rand_ctx: *mut RandContext, rand_gen: *const RandGen) -> uint8_t; 104 | pub fn ntru_rand_default_generate(rand_data: *mut uint8_t, 105 | len: uint16_t, 106 | rand_ctx: *const RandContext) 107 | -> uint8_t; 108 | pub fn ntru_rand_default_release(rand_ctx: *mut RandContext) -> uint8_t; 109 | 110 | pub fn ntru_rand_ctr_drbg_init(rand_ctx: *mut RandContext, 111 | rand_gen: *const RandGen) 112 | -> uint8_t; 113 | pub fn ntru_rand_ctr_drbg_generate(rand_data: *mut uint8_t, 114 | len: uint16_t, 115 | rand_ctx: *const RandContext) 116 | -> uint8_t; 117 | pub fn ntru_rand_ctr_drbg_release(rand_ctx: *mut RandContext) -> uint8_t; 118 | 119 | // poly.h 120 | pub fn ntru_rand_tern(n: uint16_t, 121 | num_ones: uint16_t, 122 | num_neg_ones: uint16_t, 123 | poly: *mut TernPoly, 124 | rand_ctx: *const RandContext) 125 | -> uint8_t; 126 | pub fn ntru_mult_tern(a: *const IntPoly, 127 | b: *const TernPoly, 128 | c: *mut IntPoly, 129 | mod_mask: uint16_t) 130 | -> uint8_t; 131 | pub fn ntru_mult_prod(a: *const IntPoly, 132 | b: *const ProdPoly, 133 | c: *mut IntPoly, 134 | mod_mask: uint16_t) 135 | -> uint8_t; 136 | pub fn ntru_mult_priv(a: *const PrivPoly, 137 | b: *const IntPoly, 138 | c: *mut IntPoly, 139 | mod_mask: uint16_t) 140 | -> uint8_t; 141 | pub fn ntru_mult_int(a: *const IntPoly, 142 | b: *const IntPoly, 143 | c: *mut IntPoly, 144 | mod_mask: uint16_t) 145 | -> uint8_t; 146 | pub fn ntru_add(a: *mut IntPoly, b: *const IntPoly); 147 | pub fn ntru_sub(a: *mut IntPoly, b: *const IntPoly); 148 | pub fn ntru_mod_mask(p: *mut IntPoly, mod_mask: uint16_t); 149 | pub fn ntru_mult_fac(a: *mut IntPoly, factor: int16_t); 150 | pub fn ntru_mod_center(p: *mut IntPoly, modulus: uint16_t); 151 | pub fn ntru_mod3(p: *mut IntPoly); 152 | pub fn ntru_to_arr(p: *const IntPoly, q: uint16_t, a: *mut uint8_t); 153 | pub fn ntru_from_arr(arr: *const uint8_t, n: uint16_t, q: uint16_t, p: *mut IntPoly); 154 | pub fn ntru_invert(a: *const PrivPoly, mod_mask: uint16_t, fq: *mut IntPoly) -> uint8_t; 155 | 156 | // key.h 157 | pub fn ntru_export_pub(key: *const PublicKey, arr: *mut uint8_t); 158 | pub fn ntru_import_pub(arr: *const uint8_t, key: *mut PublicKey) -> uint16_t; 159 | 160 | pub fn ntru_export_priv(key: *const PrivateKey, arr: *mut uint8_t) -> uint16_t; 161 | pub fn ntru_import_priv(arr: *const uint8_t, key: *mut PrivateKey); 162 | 163 | pub fn ntru_params_from_priv_key(key: *const PrivateKey, params: *mut EncParams) -> uint8_t; 164 | } 165 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! This crate implements the NTRU encryption library in Rust. It is an interface to libntru, even 2 | //! though many of the methods are being implemented in pure Rust. The plan is to gradually 3 | //! implement the library natively. It uses this library since it has proven to be faster than the 4 | //! original NTRU encryption implementation. In any case, it is much faster than usual encryption / 5 | //! decryption mecanisms, and quantum-proof. More on NTRU encryption 6 | //! [here](https://en.wikipedia.org/wiki/NTRUEncrypt). 7 | //! 8 | //! To use it you only need to include the following in your crate: 9 | //! 10 | //! ``` 11 | //! extern crate ntru; 12 | //! ``` 13 | //! 14 | //! NTRU encryption uses its own keys, that must be generated with the included random key 15 | //! generator, and must not be used for other applications such as NTRU signing or NTRUNMLS. 16 | //! 17 | //! # Examples 18 | //! 19 | //! ``` 20 | //! use ntru::rand::RNG_DEFAULT; 21 | //! use ntru::encparams::DEFAULT_PARAMS_256_BITS; 22 | //! 23 | //! let rand_ctx = ntru::rand::init(&RNG_DEFAULT).unwrap(); 24 | //! let kp = ntru::generate_key_pair(&DEFAULT_PARAMS_256_BITS, &rand_ctx).unwrap(); 25 | //! ``` 26 | //! 27 | //! This creates a key pair that can be uses to encrypt and decrypt messages: 28 | //! 29 | //! ``` 30 | //! # use ntru::rand::RNG_DEFAULT; 31 | //! use ntru::encparams::DEFAULT_PARAMS_256_BITS; 32 | //! # 33 | //! # let rand_ctx = ntru::rand::init(&RNG_DEFAULT).unwrap(); 34 | //! # let kp = ntru::generate_key_pair(&DEFAULT_PARAMS_256_BITS, &rand_ctx).unwrap(); 35 | //! 36 | //! let msg = b"Hello from Rust!"; 37 | //! let encrypted = ntru::encrypt(msg, kp.get_public(), &DEFAULT_PARAMS_256_BITS, 38 | //! &rand_ctx).unwrap(); 39 | //! let decrypted = ntru::decrypt(&encrypted, &kp, &DEFAULT_PARAMS_256_BITS).unwrap(); 40 | //! 41 | //! assert_eq!(&msg[..], &decrypted[..]); 42 | //! ``` 43 | 44 | #![forbid(missing_docs, warnings)] 45 | #![deny(deprecated, improper_ctypes, non_shorthand_field_patterns, overflowing_literals, 46 | plugin_as_library, private_no_mangle_fns, private_no_mangle_statics, stable_features, 47 | unconditional_recursion, unknown_lints, unused, unused_allocation, unused_attributes, 48 | unused_comparisons, unused_features, unused_parens, while_true)] 49 | #![warn(trivial_casts, trivial_numeric_casts, unused, unused_extern_crates, unused_import_braces, 50 | unused_qualifications, unused_results, variant_size_differences)] 51 | 52 | extern crate libc; 53 | 54 | pub mod types; 55 | pub mod rand; 56 | pub mod encparams; 57 | mod ffi; 58 | 59 | use types::{KeyPair, PrivateKey, PublicKey, Error}; 60 | use encparams::EncParams; 61 | use rand::RandContext; 62 | 63 | /// Key generation 64 | /// 65 | /// Generates a NTRU encryption key pair. If a deterministic RNG is used, the key pair will be 66 | /// deterministic for a given random seed; otherwise, the key pair will be completely random. 67 | pub fn generate_key_pair(params: &EncParams, rand_context: &RandContext) -> Result { 68 | let mut kp: KeyPair = Default::default(); 69 | let result = unsafe { ffi::ntru_gen_key_pair(params, &mut kp, rand_context) }; 70 | if result == 0 { 71 | Ok(kp) 72 | } else { 73 | Err(Error::from(result)) 74 | } 75 | } 76 | 77 | /// Key generation with multiple public keys 78 | /// 79 | /// Generates `num_pub` Ntru encryption key pairs. They all share a private key but their public 80 | /// keys differ. The private key decrypts messages encrypted for any of the public keys. Note that 81 | /// when decrypting, the public key of the key pair passed into `ntru_decrypt()` must match the 82 | /// public key used for encrypting the message. If a deterministic RNG is used, the key pair will 83 | /// be deterministic for a given random seed; otherwise, the key pair will be completely random. 84 | pub fn generate_multiple_key_pairs(params: &EncParams, 85 | rand_context: &RandContext, 86 | num_pub: usize) 87 | -> Result<(PrivateKey, Box<[PublicKey]>), Error> { 88 | let mut private: PrivateKey = Default::default(); 89 | let mut public: Vec = Vec::with_capacity(num_pub); 90 | for _ in 0..num_pub { 91 | public.push(Default::default()); 92 | } 93 | let result = unsafe { 94 | ffi::ntru_gen_key_pair_multi(params, 95 | &mut private, 96 | &mut public[0], 97 | rand_context, 98 | num_pub as u32) 99 | }; 100 | if result == 0 { 101 | Ok((private, public.into_boxed_slice())) 102 | } else { 103 | Err(Error::from(result)) 104 | } 105 | } 106 | 107 | /// New public key 108 | /// 109 | /// Generates a new public key for an existing private key. The new public key can be used 110 | /// interchangeably with the existing public key(s). Generating n keys via 111 | /// `ntru::generate_multiple_key_pairs()` is more efficient than generating one and then calling 112 | /// `ntru_gen_pub()` n-1 times, so if the number of public keys needed is known beforehand and if 113 | /// speed matters, `ntru_gen_key_pair_multi()` should be used. Note that when decrypting, the public 114 | /// key of the key pair passed into `ntru_decrypt()` must match the public key used for encrypting 115 | /// the message. If a deterministic RNG is used, the key will be deterministic for a given random 116 | /// seed; otherwise, the key will be completely random. 117 | pub fn generate_public(params: &EncParams, 118 | private: &PrivateKey, 119 | rand_context: &RandContext) 120 | -> Result { 121 | let mut public: PublicKey = Default::default(); 122 | let result = unsafe { ffi::ntru_gen_pub(params, private, &mut public, rand_context) }; 123 | if result == 0 { 124 | Ok(public) 125 | } else { 126 | Err(Error::from(result)) 127 | } 128 | } 129 | 130 | /// Encrypts a message 131 | /// 132 | /// If a deterministic RNG is used, the encrypted message will also be deterministic for a given 133 | /// combination of plain text, key, and random seed. See P1363.1 section 9.2.2. 134 | /// The parameters needed are the following: 135 | /// * `msg`: The message to encrypt as an ```u8``` slice. 136 | /// * `public`: The public key to encrypt the message with. 137 | /// * `params`: The NTRU encryption parameters to use. 138 | /// * `and_ctx`: An initialized random number generator. 139 | pub fn encrypt(msg: &[u8], 140 | public: &PublicKey, 141 | params: &EncParams, 142 | rand_ctx: &RandContext) 143 | -> Result, Error> { 144 | let mut enc = vec![0u8; params.enc_len() as usize]; 145 | let result = unsafe { 146 | ffi::ntru_encrypt(if msg.len() > 0 { 147 | &msg[0] 148 | } else { 149 | std::ptr::null() 150 | }, 151 | msg.len() as u16, 152 | public, 153 | params, 154 | rand_ctx, 155 | &mut enc[0]) 156 | }; 157 | 158 | if result == 0 { 159 | Ok(enc.into_boxed_slice()) 160 | } else { 161 | Err(Error::from(result)) 162 | } 163 | } 164 | 165 | /// Decrypts a message. 166 | /// 167 | /// See P1363.1 section 9.2.3. The parameters needed are the following: 168 | /// * enc: The message to decrypt as an ```u8``` slice. 169 | /// * kp: A key pair that contains the public key the message was encrypted with, and the 170 | /// corresponding private key. 171 | /// * params: Parameters the message was encrypted with 172 | pub fn decrypt(enc: &[u8], kp: &KeyPair, params: &EncParams) -> Result, Error> { 173 | let mut dec = vec![0u8; params.max_msg_len() as usize]; 174 | let mut dec_len = 0u16; 175 | let result = unsafe { ffi::ntru_decrypt(&enc[0], kp, params, &mut dec[0], &mut dec_len) }; 176 | 177 | if result == 0 { 178 | let mut final_dec = Vec::with_capacity(dec_len as usize); 179 | final_dec.extend(dec.into_iter().take(dec_len as usize)); 180 | Ok(final_dec.into_boxed_slice()) 181 | } else { 182 | Err(Error::from(result)) 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /src/rand.rs: -------------------------------------------------------------------------------- 1 | //! Rand module 2 | //! 3 | //! This module includes all the needed structs and functions to interact with the randomness 4 | //! needed by NTRU. Both, key generation and encryption need a source of randomness, for that they 5 | //! need a `RandContext`, that can be generated from a `RandGen`. The recommended RNG is the 6 | //! `RNG_DEFAULT`. If needed, in this module random data can be generated with the `generate()` 7 | //! function. Also both random `TernPoly` and `ProdPoly` can be generated. 8 | use std::{slice, ptr}; 9 | use libc::{uint8_t, uint16_t, c_void}; 10 | use types::{Error, TernPoly}; 11 | use super::ffi; 12 | 13 | /// A random context for key generation and encryption 14 | #[repr(C)] 15 | pub struct RandContext { 16 | /// The RNG for the RandContext 17 | pub rand_gen: *const RandGen, 18 | /// For deterministic RNGs 19 | pub seed: *const uint8_t, 20 | /// For deterministic RNGs 21 | pub seed_len: uint16_t, 22 | /// The current context state 23 | pub state: *const c_void, 24 | } 25 | 26 | impl Default for RandContext { 27 | fn default() -> RandContext { 28 | RandContext { 29 | rand_gen: &mut RNG_DEFAULT, 30 | seed: ptr::null(), 31 | seed_len: 0, 32 | state: ptr::null(), 33 | } 34 | } 35 | } 36 | 37 | impl Drop for RandContext { 38 | fn drop(&mut self) { 39 | let result = unsafe { ffi::ntru_rand_release(self) }; 40 | if result != 0 { 41 | panic!() 42 | } 43 | } 44 | } 45 | 46 | impl RandContext { 47 | /// Gets the seed for the RandContext 48 | pub fn get_seed(&self) -> &[u8] { 49 | unsafe { slice::from_raw_parts(self.seed, self.seed_len as usize) } 50 | } 51 | 52 | /// Gets the RNG of the RandContext 53 | pub fn get_rng(&self) -> &RandGen { 54 | unsafe { &*self.rand_gen } 55 | } 56 | } 57 | 58 | #[repr(C)] 59 | /// Random number generator 60 | pub struct RandGen { 61 | /// Random number generator initialization function 62 | init_fn: unsafe extern "C" fn(rand_ctx: *mut RandContext, rand_gen: *const RandGen) 63 | -> uint8_t, 64 | /// A pointer to a function that takes an array and an array size, and fills the array with 65 | /// random data 66 | generate_fn: unsafe extern "C" fn(rand_data: *mut uint8_t, 67 | len: uint16_t, 68 | rand_ctx: *const RandContext) 69 | -> uint8_t, 70 | /// The rng release function 71 | release_fn: unsafe extern "C" fn(rand_ctx: *mut RandContext) -> uint8_t, 72 | } 73 | 74 | impl RandGen { 75 | /// Initialize a new random contex 76 | pub fn init(&self, rand_gen: &RandGen) -> Result { 77 | let mut rand_ctx: RandContext = Default::default(); 78 | let result = unsafe { (self.init_fn)(&mut rand_ctx, rand_gen) }; 79 | if result == 1 { 80 | Ok(rand_ctx) 81 | } else { 82 | Err(Error::Prng) 83 | } 84 | } 85 | 86 | /// Generate random data 87 | pub fn generate(&self, length: u16, rand_ctx: &RandContext) -> Result, Error> { 88 | let mut plain = vec![0u8; length as usize]; 89 | let result = unsafe { (self.generate_fn)(&mut plain[0], length, rand_ctx) }; 90 | 91 | if result == 1 { 92 | Ok(plain.into_boxed_slice()) 93 | } else { 94 | Err(Error::Prng) 95 | } 96 | } 97 | } 98 | 99 | #[cfg(target_os = "windows")] 100 | /// Default Windows RNG, CryptGenRandom() 101 | pub const RNG_WINCRYPT: RandGen = RandGen { 102 | init_fn: ffi::ntru_rand_wincrypt_init, 103 | generate_fn: ffi::ntru_rand_wincrypt_generate, 104 | release_fn: ffi::ntru_rand_wincrypt_release, 105 | }; 106 | 107 | #[cfg(not(target_os = "windows"))] 108 | /// Unix default RNG, /dev/urandom 109 | pub const RNG_DEVURANDOM: RandGen = RandGen { 110 | init_fn: ffi::ntru_rand_devurandom_init, 111 | generate_fn: ffi::ntru_rand_devurandom_generate, 112 | release_fn: ffi::ntru_rand_devurandom_release, 113 | }; 114 | #[cfg(not(target_os = "windows"))] 115 | /// Unix RNG, /dev/random 116 | pub const RNG_DEVRANDOM: RandGen = RandGen { 117 | init_fn: ffi::ntru_rand_devrandom_init, 118 | generate_fn: ffi::ntru_rand_devrandom_generate, 119 | release_fn: ffi::ntru_rand_devrandom_release, 120 | }; 121 | 122 | /// Default RNG 123 | /// 124 | /// `CTR_DRBG` seeded from `/dev/urandom` (on *nix) or `CryptGenRandom()` (on Windows) 125 | pub const RNG_DEFAULT: RandGen = RandGen { 126 | init_fn: ffi::ntru_rand_default_init, 127 | generate_fn: ffi::ntru_rand_default_generate, 128 | release_fn: ffi::ntru_rand_default_release, 129 | }; 130 | 131 | /// Deterministic RNG based on `CTR_DRBG` 132 | pub const RNG_CTR_DRBG: RandGen = RandGen { 133 | init_fn: ffi::ntru_rand_ctr_drbg_init, 134 | generate_fn: ffi::ntru_rand_ctr_drbg_generate, 135 | release_fn: ffi::ntru_rand_ctr_drbg_release, 136 | }; 137 | 138 | /// Initialize a new rand context 139 | pub fn init(rand_gen: &RandGen) -> Result { 140 | let mut rand_ctx: RandContext = Default::default(); 141 | let result = unsafe { ffi::ntru_rand_init(&mut rand_ctx, rand_gen) }; 142 | if result == 0 { 143 | Ok(rand_ctx) 144 | } else { 145 | Err(Error::from(result)) 146 | } 147 | } 148 | 149 | /// Generate a new deterministic rand context 150 | pub fn init_det(rand_gen: &RandGen, seed: &[u8]) -> Result { 151 | let mut rand_ctx: RandContext = Default::default(); 152 | let result = unsafe { 153 | ffi::ntru_rand_init_det(&mut rand_ctx, rand_gen, &seed[0], seed.len() as uint16_t) 154 | }; 155 | if result == 0 { 156 | Ok(rand_ctx) 157 | } else { 158 | Err(Error::from(result)) 159 | } 160 | } 161 | 162 | /// Generate random data 163 | pub fn generate(length: u16, rand_ctx: &RandContext) -> Result, Error> { 164 | let mut plain = vec![0u8; length as usize]; 165 | let result = unsafe { ffi::ntru_rand_generate(&mut plain[0], length, rand_ctx) }; 166 | 167 | if result == 0 { 168 | Ok(plain.into_boxed_slice()) 169 | } else { 170 | Err(Error::from(result)) 171 | } 172 | } 173 | 174 | impl TernPoly { 175 | /// Random ternary polynomial 176 | /// 177 | /// Generates a random ternary polynomial. If an error occurs, it will return None. 178 | pub fn rand(n: u16, 179 | num_ones: u16, 180 | num_neg_ones: u16, 181 | rand_ctx: &RandContext) 182 | -> Option { 183 | let mut poly: TernPoly = Default::default(); 184 | let result = unsafe { ffi::ntru_rand_tern(n, num_ones, num_neg_ones, &mut poly, rand_ctx) }; 185 | 186 | if result == 0 { None } else { Some(poly) } 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /src/types.rs: -------------------------------------------------------------------------------- 1 | //! NTRU type definitions 2 | //! 3 | //! This module includes all the needed structs and enums for NTRU encryption library. All of them 4 | //! with their needed methods. 5 | use std::ops::{Add, Sub}; 6 | use std::default::Default; 7 | use std::{fmt, mem, error}; 8 | use libc::{int16_t, uint8_t, uint16_t}; 9 | use ffi; 10 | use encparams::EncParams; 11 | use rand::RandContext; 12 | 13 | /// Max `N` value for all param sets; +1 for `ntru_invert_...()` 14 | pub const MAX_DEGREE: usize = (1499 + 1); 15 | /// (Max `coefficients` + 16) rounded to a multiple of 8 16 | const INT_POLY_SIZE: usize = ((MAX_DEGREE + 16 + 7) & 0xFFF8); 17 | /// `max(df1, df2, df3, dg)` 18 | pub const MAX_ONES: usize = 499; 19 | 20 | #[repr(C)] 21 | /// A polynomial with integer coefficients. 22 | pub struct IntPoly { 23 | /// The number of coefficients 24 | n: uint16_t, 25 | /// The coefficients 26 | coeffs: [int16_t; INT_POLY_SIZE], 27 | } 28 | 29 | impl Default for IntPoly { 30 | fn default() -> IntPoly { 31 | IntPoly { 32 | n: 0, 33 | coeffs: [0; INT_POLY_SIZE], 34 | } 35 | } 36 | } 37 | 38 | impl Clone for IntPoly { 39 | fn clone(&self) -> IntPoly { 40 | let mut new_coeffs = [0i16; INT_POLY_SIZE]; 41 | new_coeffs.clone_from_slice(&self.coeffs); 42 | 43 | IntPoly { 44 | n: self.n, 45 | coeffs: new_coeffs, 46 | } 47 | } 48 | } 49 | 50 | impl Add for IntPoly { 51 | type Output = IntPoly; 52 | fn add(self, rhs: IntPoly) -> Self::Output { 53 | let mut out = self.clone(); 54 | unsafe { ffi::ntru_add(&mut out, &rhs) }; 55 | out 56 | } 57 | } 58 | 59 | impl Sub for IntPoly { 60 | type Output = IntPoly; 61 | fn sub(self, rhs: IntPoly) -> Self::Output { 62 | let mut out = self.clone(); 63 | unsafe { ffi::ntru_sub(&mut out, &rhs) }; 64 | out 65 | } 66 | } 67 | 68 | impl fmt::Debug for IntPoly { 69 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 70 | write!(f, 71 | "{{ n: {}, coeffs: [{}...{}] }}", 72 | self.n, 73 | self.coeffs[0], 74 | self.coeffs[INT_POLY_SIZE - 1]) 75 | } 76 | } 77 | 78 | impl PartialEq for IntPoly { 79 | fn eq(&self, other: &IntPoly) -> bool { 80 | self.n == other.n && 81 | { 82 | for i in 0..self.n as usize { 83 | if self.coeffs[i] != other.coeffs[i] { 84 | return false; 85 | } 86 | } 87 | true 88 | } 89 | } 90 | } 91 | 92 | impl IntPoly { 93 | /// Create a new IntPoly 94 | pub fn new(coeffs: &[i16]) -> IntPoly { 95 | let mut new_coeffs = [0; INT_POLY_SIZE]; 96 | 97 | for (i, coeff) in coeffs.iter().enumerate() { 98 | new_coeffs[i] = *coeff; 99 | } 100 | IntPoly { 101 | n: coeffs.len() as u16, 102 | coeffs: new_coeffs, 103 | } 104 | } 105 | 106 | /// Create a new random IntPoly 107 | pub fn rand(n: u16, pow2q: u16, rand_ctx: &RandContext) -> IntPoly { 108 | let rand_data = rand_ctx.get_rng().generate(n * 2, rand_ctx).unwrap(); 109 | 110 | let mut coeffs = [0i16; INT_POLY_SIZE]; 111 | let shift = 16 - pow2q; 112 | for i in (n as usize)..0usize { 113 | coeffs[i] = rand_data[i] as i16 >> shift; 114 | } 115 | 116 | IntPoly { 117 | n: n, 118 | coeffs: coeffs, 119 | } 120 | } 121 | 122 | /// Convert array to IntPoly 123 | pub fn from_arr(arr: &[u8], n: u16, q: u16) -> IntPoly { 124 | let mut p: IntPoly = Default::default(); 125 | unsafe { ffi::ntru_from_arr(&arr[0], n, q, &mut p) }; 126 | 127 | p 128 | } 129 | 130 | /// Get the coefficients 131 | pub fn get_coeffs(&self) -> &[i16] { 132 | &self.coeffs[0..self.n as usize] 133 | } 134 | 135 | /// Set the coefficients 136 | pub fn set_coeffs(&mut self, coeffs: &[i16]) { 137 | self.coeffs = [0; INT_POLY_SIZE]; 138 | for (i, coeff) in coeffs.iter().enumerate() { 139 | self.coeffs[i] = *coeff; 140 | } 141 | } 142 | 143 | /// Set a coefficient 144 | pub fn set_coeff(&mut self, index: usize, value: i16) { 145 | self.coeffs[index] = value 146 | } 147 | 148 | /// Modifies the IntPoly with the given mask 149 | pub fn mod_mask(&mut self, mod_mask: u16) { 150 | unsafe { ffi::ntru_mod_mask(self, mod_mask) }; 151 | } 152 | 153 | /// Converts the IntPoly to a byte array using 32 bit arithmetic 154 | pub fn to_arr(&self, params: &EncParams) -> Box<[u8]> { 155 | let mut a = vec![0u8; params.enc_len() as usize]; 156 | unsafe { ffi::ntru_to_arr(self, params.get_q(), &mut a[0]) }; 157 | 158 | a.into_boxed_slice() 159 | } 160 | 161 | /// General polynomial by ternary polynomial multiplication 162 | /// 163 | /// Multiplies a IntPoly by a TernPoly. The number of coefficients must be the same for both 164 | /// polynomials. It also returns if the number of coefficients differ or not. 165 | pub fn mult_tern(&self, b: &TernPoly, mod_mask: u16) -> (IntPoly, bool) { 166 | if self.n != b.n { 167 | panic!("To multiply a IntPoly by a TernPoly the number of coefficients must \ 168 | be the same for both polynomials") 169 | } 170 | let mut c: IntPoly = Default::default(); 171 | let result = unsafe { ffi::ntru_mult_tern(self, b, &mut c, mod_mask) }; 172 | (c, result == 1) 173 | } 174 | 175 | /// Add a ternary polynomial 176 | /// 177 | /// Adds a ternary polynomial to the general polynomial. Returns a new general polynomial. 178 | pub fn add_tern(&self, b: &TernPoly) -> IntPoly { 179 | IntPoly { 180 | n: self.n, 181 | coeffs: { 182 | let mut coeffs = [0; INT_POLY_SIZE]; 183 | let tern_ones = b.get_ones(); 184 | let tern_neg_ones = b.get_neg_ones(); 185 | 186 | for one in tern_ones.iter() { 187 | coeffs[*one as usize] = self.coeffs[*one as usize] + 1; 188 | } 189 | 190 | for neg_one in tern_neg_ones.iter() { 191 | coeffs[*neg_one as usize] = self.coeffs[*neg_one as usize] + 1; 192 | } 193 | coeffs 194 | }, 195 | } 196 | } 197 | 198 | /// General polynomial by product-form polynomial multiplication 199 | /// 200 | /// Multiplies a IntPoly by a ProdPoly. The number of coefficients must be the same for both 201 | /// polynomials. It also returns if the number of coefficients differ or not. 202 | pub fn mult_prod(&self, b: &ProdPoly, mod_mask: u16) -> (IntPoly, bool) { 203 | if self.n != b.n { 204 | panic!("To multiply a IntPoly by a ProdPoly the number of coefficients must \ 205 | be the same for both polynomials") 206 | } 207 | let mut c: IntPoly = Default::default(); 208 | let result = unsafe { ffi::ntru_mult_prod(self, b, &mut c, mod_mask) }; 209 | (c, result == 1) 210 | } 211 | 212 | /// General polynomial by private polynomial multiplication 213 | /// 214 | /// Multiplies a IntPoly by a PrivPoly, i.e. a TernPoly or a ProdPoly. The number of 215 | /// coefficients must be the same for both polynomials. It also returns if the number of 216 | /// coefficients differ or not. 217 | pub fn mult_priv(&self, b: &PrivPoly, mod_mask: u16) -> (IntPoly, bool) { 218 | if (b.is_product() && self.n != b.get_poly_prod().n) || 219 | (!b.is_product() && self.n != b.get_poly_tern().n) { 220 | panic!("To multiply a IntPoly by a ProdPoly the number of coefficients must \ 221 | be the same for both polynomials") 222 | } 223 | let mut c: IntPoly = Default::default(); 224 | let result = unsafe { ffi::ntru_mult_priv(b, self, &mut c, mod_mask) }; 225 | (c, result == 1) 226 | } 227 | 228 | /// General polynomial by general polynomial multiplication 229 | /// 230 | /// Multiplies a IntPoly by another IntPoly, i.e. a TernPoly or a ProdPoly. The number of 231 | /// coefficients must be the same for both polynomials. It also returns if the number of 232 | /// coefficients differ or not. 233 | pub fn mult_int(&self, b: &IntPoly, mod_mask: u16) -> (IntPoly, bool) { 234 | let mut c: IntPoly = Default::default(); 235 | let result = unsafe { ffi::ntru_mult_int(self, b, &mut c, mod_mask) }; 236 | (c, result == 1) 237 | } 238 | 239 | /// Multiply by factor 240 | pub fn mult_fac(&mut self, factor: i16) { 241 | unsafe { ffi::ntru_mult_fac(self, factor) }; 242 | } 243 | 244 | /// Calls `ntru_mod_center()` in this polinomial. 245 | pub fn mod_center(&mut self, modulus: u16) { 246 | unsafe { ffi::ntru_mod_center(self, modulus) }; 247 | } 248 | 249 | /// Calls `ntru_mod3()` in this polinomial. 250 | pub fn mod3(&mut self) { 251 | unsafe { ffi::ntru_mod3(self) }; 252 | } 253 | 254 | /// Check if both polynomials are equals given a modulus 255 | pub fn equals_mod(&self, other: &IntPoly, modulus: u16) -> bool { 256 | self.n == other.n && 257 | { 258 | for i in 0..self.n as usize { 259 | if (self.coeffs[i] - other.coeffs[i]) as i32 % modulus as i32 != 0 { 260 | return false; 261 | } 262 | } 263 | true 264 | } 265 | } 266 | 267 | /// Check if the IntPoly equals 1 268 | pub fn equals1(&self) -> bool { 269 | for i in 1..self.n { 270 | if self.coeffs[i as usize] != 0 { 271 | return false; 272 | } 273 | } 274 | self.coeffs[0] == 1 275 | } 276 | } 277 | 278 | #[repr(C)] 279 | /// A ternary polynomial, i.e. all coefficients are equal to -1, 0, or 1. 280 | pub struct TernPoly { 281 | n: uint16_t, 282 | num_ones: uint16_t, 283 | num_neg_ones: uint16_t, 284 | ones: [uint16_t; MAX_ONES], 285 | neg_ones: [uint16_t; MAX_ONES], 286 | } 287 | 288 | impl Default for TernPoly { 289 | fn default() -> TernPoly { 290 | TernPoly { 291 | n: 0, 292 | num_ones: 0, 293 | num_neg_ones: 0, 294 | ones: [0; MAX_ONES], 295 | neg_ones: [0; MAX_ONES], 296 | } 297 | } 298 | } 299 | 300 | impl Clone for TernPoly { 301 | fn clone(&self) -> TernPoly { 302 | let mut new_ones = [0u16; MAX_ONES]; 303 | new_ones.clone_from_slice(&self.ones); 304 | let mut new_neg_ones = [0u16; MAX_ONES]; 305 | new_neg_ones.clone_from_slice(&self.neg_ones); 306 | 307 | TernPoly { 308 | n: self.n, 309 | num_ones: self.num_ones, 310 | num_neg_ones: self.num_neg_ones, 311 | ones: new_ones, 312 | neg_ones: new_neg_ones, 313 | } 314 | } 315 | } 316 | 317 | impl fmt::Debug for TernPoly { 318 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 319 | write!(f, 320 | "{{ n: {}, num_ones: {}, num_neg_ones: {}, ones: [{}...{}], neg_ones: [{}...{}] }}", 321 | self.n, 322 | self.num_ones, 323 | self.num_neg_ones, 324 | self.ones[0], 325 | self.ones[MAX_ONES - 1], 326 | self.neg_ones[0], 327 | self.neg_ones[MAX_ONES - 1]) 328 | } 329 | } 330 | 331 | impl PartialEq for TernPoly { 332 | fn eq(&self, other: &TernPoly) -> bool { 333 | self.n == other.n && self.num_ones == other.num_ones && 334 | self.num_neg_ones == other.num_neg_ones && 335 | { 336 | for i in 0..MAX_ONES { 337 | if self.ones[i] != other.ones[i] { 338 | return false; 339 | } 340 | if self.neg_ones[i] != other.neg_ones[i] { 341 | return false; 342 | } 343 | } 344 | true 345 | } 346 | } 347 | } 348 | 349 | impl TernPoly { 350 | /// Creates a new TernPoly 351 | pub fn new(n: u16, ones: &[u16], neg_ones: &[u16]) -> TernPoly { 352 | let mut new_ones = [0; MAX_ONES]; 353 | let mut new_neg_ones = [0; MAX_ONES]; 354 | 355 | for (i, one) in ones.iter().enumerate() { 356 | new_ones[i] = *one; 357 | } 358 | 359 | for (i, neg_one) in neg_ones.iter().enumerate() { 360 | new_neg_ones[i] = *neg_one; 361 | } 362 | 363 | TernPoly { 364 | n: n, 365 | num_ones: ones.len() as u16, 366 | num_neg_ones: neg_ones.len() as u16, 367 | ones: new_ones, 368 | neg_ones: new_neg_ones, 369 | } 370 | } 371 | 372 | /// Get the 373 | pub fn get_n(&self) -> u16 { 374 | self.n 375 | } 376 | 377 | /// Get +1 coefficients 378 | pub fn get_ones(&self) -> &[u16] { 379 | &self.ones[0..self.num_ones as usize] 380 | } 381 | 382 | /// Get -1 coefficients 383 | pub fn get_neg_ones(&self) -> &[u16] { 384 | &self.neg_ones[0..self.num_neg_ones as usize] 385 | } 386 | 387 | /// Ternary to general integer polynomial 388 | /// 389 | /// Converts a TernPoly to an equivalent IntPoly. 390 | pub fn to_int_poly(&self) -> IntPoly { 391 | IntPoly { 392 | n: self.n, 393 | coeffs: { 394 | let mut coeffs = [0; INT_POLY_SIZE]; 395 | 396 | for i in 0..self.num_ones { 397 | coeffs[self.ones[i as usize] as usize] = 1; 398 | } 399 | for i in 0..self.num_neg_ones { 400 | coeffs[self.neg_ones[i as usize] as usize] = -1; 401 | } 402 | 403 | coeffs 404 | }, 405 | } 406 | } 407 | } 408 | 409 | #[repr(C)] 410 | #[derive(Debug, PartialEq, Clone)] 411 | /// A product-form polynomial, i.e. a polynomial of the form f1*f2+f3 where f1,f2,f3 are very 412 | /// sparsely populated ternary polynomials. 413 | pub struct ProdPoly { 414 | n: uint16_t, 415 | f1: TernPoly, 416 | f2: TernPoly, 417 | f3: TernPoly, 418 | } 419 | 420 | impl Default for ProdPoly { 421 | fn default() -> ProdPoly { 422 | ProdPoly { 423 | n: 0, 424 | f1: Default::default(), 425 | f2: Default::default(), 426 | f3: Default::default(), 427 | } 428 | } 429 | } 430 | 431 | impl ProdPoly { 432 | /// Creates a new `ProdPoly` from three `TernPoly`s 433 | pub fn new(n: u16, f1: TernPoly, f2: TernPoly, f3: TernPoly) -> ProdPoly { 434 | ProdPoly { 435 | n: n, 436 | f1: f1, 437 | f2: f2, 438 | f3: f3, 439 | } 440 | } 441 | 442 | /// Random product-form polynomial 443 | /// 444 | /// Generates a random product-form polynomial consisting of 3 random ternary polynomials. 445 | /// Parameters: 446 | /// 447 | /// * *N*: the number of coefficients, must be MAX_DEGREE or less 448 | /// * *df1*: number of ones and negative ones in the first ternary polynomial 449 | /// * *df2*: number of ones and negative ones in the second ternary polynomial 450 | /// * *df3_ones*: number of ones ones in the third ternary polynomial 451 | /// * *df3_neg_ones*: number of negative ones in the third ternary polynomial 452 | /// * *rand_ctx*: a random number generator 453 | pub fn rand(n: u16, 454 | df1: u16, 455 | df2: u16, 456 | df3_ones: u16, 457 | df3_neg_ones: u16, 458 | rand_ctx: &RandContext) 459 | -> Option { 460 | let f1 = TernPoly::rand(n, df1, df1, rand_ctx); 461 | if f1.is_none() { 462 | return None; 463 | } 464 | let f1 = f1.unwrap(); 465 | 466 | let f2 = TernPoly::rand(n, df2, df2, rand_ctx); 467 | if f2.is_none() { 468 | return None; 469 | } 470 | let f2 = f2.unwrap(); 471 | 472 | let f3 = TernPoly::rand(n, df3_ones, df3_neg_ones, rand_ctx); 473 | if f3.is_none() { 474 | return None; 475 | } 476 | let f3 = f3.unwrap(); 477 | 478 | Some(ProdPoly::new(n, f1, f2, f3)) 479 | } 480 | 481 | /// Returns an IntPoly equivalent to the ProdPoly 482 | pub fn to_int_poly(&self, modulus: u16) -> IntPoly { 483 | let c = IntPoly { 484 | n: self.n, 485 | coeffs: [0; INT_POLY_SIZE], 486 | }; 487 | 488 | let mod_mask = modulus - 1; 489 | let (c, _) = c.mult_tern(&self.f2, mod_mask); 490 | c.add_tern(&self.f3) 491 | } 492 | } 493 | 494 | /// The size of the union in 16 bit words 495 | const PRIVUNION_SIZE: usize = 3004; 496 | 497 | #[repr(C)] 498 | /// Union for the private key polynomial 499 | struct PrivUnion { 500 | /// The union data as a 2-byte array 501 | data: [uint16_t; PRIVUNION_SIZE], 502 | } 503 | 504 | impl Default for PrivUnion { 505 | fn default() -> PrivUnion { 506 | PrivUnion { data: [0; PRIVUNION_SIZE] } 507 | } 508 | } 509 | 510 | impl Clone for PrivUnion { 511 | fn clone(&self) -> PrivUnion { 512 | let mut new_data = [0u16; PRIVUNION_SIZE]; 513 | for (i, data) in self.data.iter().enumerate() { 514 | new_data[i] = *data 515 | } 516 | PrivUnion { data: new_data } 517 | } 518 | } 519 | 520 | impl PrivUnion { 521 | /// Create a new union from a ProdPoly 522 | unsafe fn new_from_prod(poly: ProdPoly) -> PrivUnion { 523 | let arr: &[uint16_t; 3004] = mem::transmute(&poly); 524 | let mut data = [0; PRIVUNION_SIZE]; 525 | 526 | for (i, b) in arr.iter().enumerate() { 527 | data[i] = *b; 528 | } 529 | 530 | PrivUnion { data: data } 531 | } 532 | 533 | /// Create a new union from a TernPoly 534 | unsafe fn new_from_tern(poly: TernPoly) -> PrivUnion { 535 | let arr: &[uint16_t; 1001] = mem::transmute(&poly); 536 | let mut data = [0; PRIVUNION_SIZE]; 537 | 538 | for (i, b) in arr.iter().enumerate() { 539 | data[i] = *b; 540 | } 541 | 542 | PrivUnion { data: data } 543 | } 544 | 545 | /// Get the union as a ProdPoly 546 | unsafe fn prod(&self) -> &ProdPoly { 547 | mem::transmute(&self.data) 548 | } 549 | 550 | /// Get the union as a TernPoly 551 | unsafe fn tern(&self) -> &TernPoly { 552 | mem::transmute(&self.data) 553 | } 554 | } 555 | 556 | #[repr(C)] 557 | #[derive(Clone)] 558 | /// Private polynomial, can be ternary or product-form 559 | pub struct PrivPoly { 560 | // maybe we could do conditional compilation? 561 | /// Whether the polynomial is in product form 562 | prod_flag: uint8_t, 563 | poly: PrivUnion, 564 | } 565 | 566 | impl Default for PrivPoly { 567 | fn default() -> PrivPoly { 568 | PrivPoly { 569 | prod_flag: 0, 570 | poly: Default::default(), 571 | } 572 | } 573 | } 574 | 575 | impl fmt::Debug for PrivPoly { 576 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 577 | if self.is_product() { 578 | write!(f, "PrivPoly {{ prod_poly: {:?} }}", self.get_poly_prod()) 579 | } else { 580 | write!(f, "PrivPoly {{ tern_poly: {:?} }}", self.get_poly_tern()) 581 | } 582 | } 583 | } 584 | 585 | impl PartialEq for PrivPoly { 586 | fn eq(&self, other: &PrivPoly) -> bool { 587 | self.prod_flag == other.prod_flag && 588 | { 589 | if self.prod_flag > 0 { 590 | self.get_poly_prod() == other.get_poly_prod() 591 | } else { 592 | self.get_poly_tern() == other.get_poly_tern() 593 | } 594 | } 595 | } 596 | } 597 | 598 | impl PrivPoly { 599 | /// Create a new PrivPoly with a ProdPoly 600 | pub fn new_with_prod_poly(poly: ProdPoly) -> PrivPoly { 601 | PrivPoly { 602 | prod_flag: 1, 603 | poly: unsafe { PrivUnion::new_from_prod(poly) }, 604 | } 605 | } 606 | 607 | /// Create a new PrivPoly with a TernPoly 608 | pub fn new_with_tern_poly(poly: TernPoly) -> PrivPoly { 609 | PrivPoly { 610 | prod_flag: 0, 611 | poly: unsafe { PrivUnion::new_from_tern(poly) }, 612 | } 613 | } 614 | 615 | /// If the PrivPoly contains a ProdPoly 616 | pub fn is_product(&self) -> bool { 617 | self.prod_flag == 1 618 | } 619 | 620 | /// Get the ProdPoly of the union 621 | /// 622 | /// Panics if the union is actually a TernPoly 623 | pub fn get_poly_prod(&self) -> &ProdPoly { 624 | if self.prod_flag != 1 { 625 | panic!("Trying to get PrivPoly from an union that is TernPoly."); 626 | } 627 | unsafe { &*self.poly.prod() } 628 | } 629 | 630 | /// Get the TernPoly of the union 631 | /// 632 | /// Panics if the union is actually a ProdPoly 633 | pub fn get_poly_tern(&self) -> &TernPoly { 634 | if self.prod_flag != 0 { 635 | panic!("Trying to get TernPoly from an union that is ProdPoly."); 636 | } 637 | unsafe { &*self.poly.tern() } 638 | } 639 | 640 | /// Inverse modulo q 641 | /// 642 | /// Computes the inverse of 1+3a mod q; q must be a power of 2. It also returns if the 643 | /// polynomial is invertible. 644 | /// 645 | /// The algorithm is described in "Almost Inverses and Fast NTRU Key Generation" at 646 | /// http://www.securityinnovation.com/uploads/Crypto/NTRUTech014.pdf 647 | pub fn invert(&self, mod_mask: u16) -> (IntPoly, bool) { 648 | let mut fq: IntPoly = Default::default(); 649 | let result = unsafe { ffi::ntru_invert(self, mod_mask, &mut fq) }; 650 | 651 | (fq, result == 1) 652 | } 653 | } 654 | 655 | #[repr(C)] 656 | #[derive(Debug, PartialEq, Clone)] 657 | /// NTRU encryption private key 658 | pub struct PrivateKey { 659 | q: uint16_t, 660 | t: PrivPoly, 661 | } 662 | 663 | impl Default for PrivateKey { 664 | fn default() -> PrivateKey { 665 | PrivateKey { 666 | q: 0, 667 | t: Default::default(), 668 | } 669 | } 670 | } 671 | 672 | impl PrivateKey { 673 | /// Gets the q parameter of the PrivateKey 674 | pub fn get_q(&self) -> u16 { 675 | self.q 676 | } 677 | 678 | /// Gets the tparameter of the PrivateKey 679 | pub fn get_t(&self) -> &PrivPoly { 680 | &self.t 681 | } 682 | 683 | /// Get params from the private key 684 | pub fn get_params(&self) -> Result { 685 | let mut params: EncParams = Default::default(); 686 | let result = unsafe { ffi::ntru_params_from_priv_key(self, &mut params) }; 687 | 688 | if result == 0 { 689 | Ok(params) 690 | } else { 691 | Err(Error::from(result)) 692 | } 693 | } 694 | 695 | /// Import private key 696 | pub fn import(arr: &[u8]) -> PrivateKey { 697 | let mut key: PrivateKey = Default::default(); 698 | unsafe { ffi::ntru_import_priv(&arr[0], &mut key) }; 699 | 700 | key 701 | } 702 | 703 | /// Export private key 704 | pub fn export(&self, params: &EncParams) -> Box<[u8]> { 705 | let mut arr = vec![0u8; params.private_len() as usize]; 706 | let _ = unsafe { ffi::ntru_export_priv(self, &mut arr[..][0]) }; 707 | 708 | arr.into_boxed_slice() 709 | } 710 | } 711 | 712 | #[repr(C)] 713 | #[derive(Debug, PartialEq, Clone)] 714 | /// NTRU encryption public key 715 | pub struct PublicKey { 716 | q: uint16_t, 717 | h: IntPoly, 718 | } 719 | 720 | impl Default for PublicKey { 721 | fn default() -> PublicKey { 722 | PublicKey { 723 | q: 0, 724 | h: Default::default(), 725 | } 726 | } 727 | } 728 | 729 | impl PublicKey { 730 | /// Get the q parameter of the PublicKey 731 | pub fn get_q(&self) -> u16 { 732 | self.q 733 | } 734 | 735 | /// Get the h parameter of the PublicKey 736 | pub fn get_h(&self) -> &IntPoly { 737 | &self.h 738 | } 739 | 740 | /// Import a public key 741 | pub fn import(arr: &[u8]) -> PublicKey { 742 | let mut key: PublicKey = Default::default(); 743 | let _ = unsafe { ffi::ntru_import_pub(&arr[0], &mut key) }; 744 | 745 | key 746 | } 747 | 748 | /// Export public key 749 | pub fn export(&self, params: &EncParams) -> Box<[u8]> { 750 | let mut arr = vec![0u8; params.public_len() as usize]; 751 | unsafe { ffi::ntru_export_pub(self, &mut arr[..][0]) }; 752 | 753 | arr.into_boxed_slice() 754 | } 755 | } 756 | 757 | #[repr(C)] 758 | #[derive(Debug, PartialEq, Clone)] 759 | /// NTRU encryption key pair 760 | pub struct KeyPair { 761 | /// Private key 762 | private: PrivateKey, 763 | /// Public key 764 | public: PublicKey, 765 | } 766 | 767 | impl Default for KeyPair { 768 | fn default() -> KeyPair { 769 | KeyPair { 770 | private: Default::default(), 771 | public: Default::default(), 772 | } 773 | } 774 | } 775 | 776 | impl KeyPair { 777 | /// Generate a new key pair 778 | pub fn new(private: PrivateKey, public: PublicKey) -> KeyPair { 779 | KeyPair { 780 | private: private, 781 | public: public, 782 | } 783 | } 784 | 785 | /// Get params from the key pair 786 | pub fn get_params(&self) -> Result { 787 | self.private.get_params() 788 | } 789 | 790 | /// The private key 791 | pub fn get_private(&self) -> &PrivateKey { 792 | &self.private 793 | } 794 | /// The public key 795 | pub fn get_public(&self) -> &PublicKey { 796 | &self.public 797 | } 798 | } 799 | 800 | /// The error enum 801 | #[derive(Debug, PartialEq, Clone, Copy)] 802 | pub enum Error { 803 | /// Out of memory error. 804 | OutOfMemory, 805 | /// Error in the random number generator. 806 | Prng, 807 | /// Message is too long. 808 | MessageTooLong, 809 | /// Invalid maximum length. 810 | InvalidMaxLength, 811 | /// MD0 violation. 812 | Md0Violation, 813 | /// No zero pad. 814 | NoZeroPad, 815 | /// Invalid encoding of the message. 816 | InvalidEncoding, 817 | /// Null argument. 818 | NullArgument, 819 | /// Unknown parameter set. 820 | UnknownParamSet, 821 | /// Invalid parameter. 822 | InvalidParam, 823 | /// Invalid key. 824 | InvalidKey, 825 | } 826 | 827 | impl fmt::Display for Error { 828 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 829 | write!(f, "{:?}", self) 830 | } 831 | } 832 | 833 | impl From for Error { 834 | fn from(error: uint8_t) -> Error { 835 | match error { 836 | 1 => Error::OutOfMemory, 837 | 2 => Error::Prng, 838 | 3 => Error::MessageTooLong, 839 | 4 => Error::InvalidMaxLength, 840 | 5 => Error::Md0Violation, 841 | 6 => Error::NoZeroPad, 842 | 7 => Error::InvalidEncoding, 843 | 8 => Error::NullArgument, 844 | 9 => Error::UnknownParamSet, 845 | 10 => Error::InvalidParam, 846 | 11 => Error::InvalidKey, 847 | _ => unreachable!(), 848 | } 849 | } 850 | } 851 | 852 | impl error::Error for Error { 853 | fn description(&self) -> &str { 854 | match *self { 855 | Error::OutOfMemory => "Out of memory error.", 856 | Error::Prng => "Error in the random number generator.", 857 | Error::MessageTooLong => "Message is too long.", 858 | Error::InvalidMaxLength => "Invalid maximum length.", 859 | Error::Md0Violation => "MD0 violation.", 860 | Error::NoZeroPad => "No zero pad.", 861 | Error::InvalidEncoding => "Invalid encoding of the message.", 862 | Error::NullArgument => "Null argument.", 863 | Error::UnknownParamSet => "Unknown parameter set.", 864 | Error::InvalidParam => "Invalid parameter.", 865 | Error::InvalidKey => "Invalid key.", 866 | } 867 | } 868 | } 869 | -------------------------------------------------------------------------------- /tests/key.rs: -------------------------------------------------------------------------------- 1 | #![forbid(missing_docs, warnings)] 2 | #![deny(deprecated, improper_ctypes, non_shorthand_field_patterns, overflowing_literals, 3 | plugin_as_library, private_no_mangle_fns, private_no_mangle_statics, stable_features, 4 | unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation, 5 | unused_attributes, unused_comparisons, unused_features, unused_parens, while_true)] 6 | #![warn(trivial_casts, trivial_numeric_casts, unused, unused_extern_crates, unused_import_braces, 7 | unused_qualifications, unused_results, variant_size_differences)] 8 | 9 | extern crate ntru; 10 | use ntru::encparams::{EES439EP1, EES1087EP2, ALL_PARAM_SETS}; 11 | use ntru::rand::RNG_DEFAULT; 12 | use ntru::types::{PublicKey, PrivateKey, PrivPoly, IntPoly}; 13 | 14 | fn ntru_priv_to_int(a: &PrivPoly, modulus: u16) -> IntPoly { 15 | if a.is_product() { 16 | a.get_poly_prod().to_int_poly(modulus) 17 | } else { 18 | a.get_poly_tern().to_int_poly() 19 | } 20 | } 21 | 22 | #[test] 23 | fn it_export_import() { 24 | let param_arr = [EES439EP1, EES1087EP2]; 25 | 26 | for params in ¶m_arr { 27 | let rng = RNG_DEFAULT; 28 | let rand_ctx = ntru::rand::init(&rng).unwrap(); 29 | let kp = ntru::generate_key_pair(params, &rand_ctx).unwrap(); 30 | 31 | // Test public key 32 | let pub_arr = kp.get_public().export(params); 33 | let imp_pub = PublicKey::import(&pub_arr); 34 | assert_eq!(kp.get_public().get_h(), imp_pub.get_h()); 35 | 36 | // Test private key 37 | let priv_arr = kp.get_private().export(params); 38 | let imp_priv = PrivateKey::import(&priv_arr); 39 | 40 | let t_int1 = ntru_priv_to_int(imp_priv.get_t(), params.get_q()); 41 | let t_int2 = ntru_priv_to_int(kp.get_private().get_t(), params.get_q()); 42 | 43 | assert_eq!(t_int1, t_int2); 44 | } 45 | } 46 | 47 | #[test] 48 | fn it_params_from_key() { 49 | let param_arr = ALL_PARAM_SETS; 50 | 51 | for params in ¶m_arr { 52 | let rng = RNG_DEFAULT; 53 | let rand_ctx = ntru::rand::init(&rng).unwrap(); 54 | 55 | let kp = ntru::generate_key_pair(params, &rand_ctx).unwrap(); 56 | 57 | let params2 = kp.get_private().get_params().unwrap(); 58 | assert_eq!(params, ¶ms2); 59 | } 60 | 61 | for (i, params1) in param_arr.iter().enumerate() { 62 | for (j, params2) in param_arr.iter().enumerate() { 63 | if params1 == params2 { 64 | assert_eq!(i, j); 65 | } else { 66 | assert!(i != j); 67 | } 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /tests/lib.rs: -------------------------------------------------------------------------------- 1 | #![forbid(missing_docs, warnings)] 2 | #![deny(deprecated, improper_ctypes, non_shorthand_field_patterns, overflowing_literals, 3 | plugin_as_library, private_no_mangle_fns, private_no_mangle_statics, stable_features, 4 | unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation, 5 | unused_attributes, unused_comparisons, unused_features, unused_parens, while_true)] 6 | #![warn(trivial_casts, trivial_numeric_casts, unused, unused_extern_crates, unused_import_braces, 7 | unused_qualifications, unused_results, variant_size_differences)] 8 | 9 | #[macro_use] 10 | extern crate ntru; 11 | extern crate crypto; 12 | extern crate rand; 13 | 14 | use crypto::digest::Digest; 15 | use crypto::sha1::Sha1; 16 | 17 | use rand::Rng; 18 | 19 | use ntru::encparams::{EncParams, ALL_PARAM_SETS}; 20 | use ntru::rand::{RNG_DEFAULT, RNG_CTR_DRBG}; 21 | use ntru::types::{IntPoly, TernPoly, PrivateKey, PublicKey, KeyPair}; 22 | 23 | fn encrypt_poly(m: IntPoly, r: &TernPoly, h: &IntPoly, q: u16) -> IntPoly { 24 | let (mut res, _) = h.mult_tern(r, q); 25 | res = res + m; 26 | res.mod_mask(q - 1); 27 | res 28 | } 29 | 30 | fn decrypt_poly(e: IntPoly, private: &PrivateKey, modulus: u16) -> IntPoly { 31 | let (mut d, _) = if private.get_t().is_product() { 32 | e.mult_prod(private.get_t().get_poly_prod(), modulus - 1) 33 | } else { 34 | e.mult_tern(private.get_t().get_poly_tern(), modulus - 1) 35 | }; 36 | d.mod_mask(modulus - 1); 37 | d.mult_fac(3); 38 | d = d + e; 39 | d.mod_center(modulus); 40 | d.mod3(); 41 | for i in 0..d.get_coeffs().len() { 42 | if d.get_coeffs()[i] == 2 { 43 | d.set_coeff(i, -1) 44 | } 45 | } 46 | d 47 | } 48 | 49 | fn gen_key_pair(seed: &str, params: &EncParams) -> KeyPair { 50 | let seed_u8 = seed.as_bytes(); 51 | let rng = RNG_CTR_DRBG; 52 | let rand_ctx = ntru::rand::init_det(&rng, seed_u8).unwrap(); 53 | 54 | ntru::generate_key_pair(params, &rand_ctx).unwrap() 55 | } 56 | 57 | fn sha1(input: &[u8]) -> [u8; 20] { 58 | let mut hasher = Sha1::new(); 59 | hasher.input(input); 60 | 61 | let mut digest = [0u8; 20]; 62 | hasher.result(&mut digest); 63 | digest 64 | } 65 | 66 | #[test] 67 | fn it_keygen() { 68 | let param_arr = &ALL_PARAM_SETS; 69 | 70 | for params in param_arr { 71 | let rand_ctx = ntru::rand::init(&RNG_DEFAULT).unwrap(); 72 | let mut kp = ntru::generate_key_pair(params, &rand_ctx).unwrap(); 73 | 74 | // Encrypt a random message 75 | let m = TernPoly::rand(params.get_n(), 76 | params.get_n() / 3, 77 | params.get_n() / 3, 78 | &rand_ctx) 79 | .unwrap(); 80 | let m_int = m.to_int_poly(); 81 | 82 | let r = TernPoly::rand(params.get_n(), 83 | params.get_n() / 3, 84 | params.get_n() / 3, 85 | &rand_ctx) 86 | .unwrap(); 87 | 88 | let e = encrypt_poly(m_int.clone(), &r, kp.get_public().get_h(), params.get_q()); 89 | 90 | // Decrypt and verify 91 | let c = decrypt_poly(e, kp.get_private(), params.get_q()); 92 | assert_eq!(m_int, c); 93 | 94 | // Test deterministic key generation 95 | kp = gen_key_pair("my test password", params); 96 | let rng = RNG_CTR_DRBG; 97 | let rand_ctx2 = ntru::rand::init_det(&rng, b"my test password").unwrap(); 98 | let kp2 = ntru::generate_key_pair(params, &rand_ctx2).unwrap(); 99 | 100 | assert_eq!(kp, kp2); 101 | } 102 | } 103 | 104 | // Tests ntru_encrypt() with a non-deterministic RNG 105 | fn test_encr_decr_nondet(params: &EncParams) { 106 | let rng = RNG_DEFAULT; 107 | let rand_ctx = ntru::rand::init(&rng).unwrap(); 108 | let kp = ntru::generate_key_pair(params, &rand_ctx).unwrap(); 109 | 110 | // Randomly choose the number of public keys for testing ntru::generate_multiple_key_pairs and 111 | // ntru::generate_public 112 | let num_pub_keys: usize = rand::thread_rng().gen_range(1, 10); 113 | 114 | // Create a key pair with multiple public keys (using ntru_gen_key_pair_multi) 115 | let (priv_multi1, pub_multi1) = 116 | ntru::generate_multiple_key_pairs(params, &rand_ctx, num_pub_keys).unwrap(); 117 | 118 | // Create a key pair with multiple public keys (using ntru::generate_public) 119 | let kp_multi2 = ntru::generate_key_pair(params, &rand_ctx).unwrap(); 120 | let mut pub_multi2 = Vec::with_capacity(num_pub_keys); 121 | for _ in 0..num_pub_keys { 122 | pub_multi2.push(ntru::generate_public(params, kp_multi2.get_private(), &rand_ctx).unwrap()); 123 | } 124 | 125 | let max_len = params.max_msg_len(); 126 | let plain = ntru::rand::generate(max_len as u16, &rand_ctx).unwrap(); 127 | 128 | for plain_len in 0..max_len + 1 { 129 | // Test single public key 130 | let encrypted = ntru::encrypt(&plain[..plain_len as usize], 131 | kp.get_public(), 132 | params, 133 | &rand_ctx) 134 | .unwrap(); 135 | let decrypted = ntru::decrypt(&encrypted, &kp, params).unwrap(); 136 | 137 | for i in 0..plain_len { 138 | assert_eq!(plain[i as usize], decrypted[i as usize]); 139 | } 140 | 141 | // Test multiple public keys 142 | for (i, pub_key) in pub_multi1.into_iter().enumerate() { 143 | let rand_value = rand::thread_rng().gen_range(1, 100); 144 | if rand_value % 100 != 0 { 145 | continue; 146 | } 147 | 148 | // Test priv_multi1/pub_multi1 149 | let encrypted = 150 | ntru::encrypt(&plain[0..plain_len as usize], pub_key, params, &rand_ctx).unwrap(); 151 | 152 | let kp_decrypt1 = KeyPair::new(priv_multi1.clone(), pub_key.clone()); 153 | let decrypted = ntru::decrypt(&encrypted, &kp_decrypt1, params).unwrap(); 154 | for i in 0..plain_len { 155 | assert_eq!(plain[i as usize], decrypted[i as usize]); 156 | } 157 | 158 | // Test kp_multi2 + pub_multi2 159 | let public = if i == 0 { 160 | kp_multi2.get_public() 161 | } else { 162 | &pub_multi2[i - 1] 163 | }; 164 | let encrypted = ntru::encrypt(&plain[0..plain_len as usize], public, params, &rand_ctx) 165 | .unwrap(); 166 | 167 | let kp_decrypt2 = KeyPair::new(kp_multi2.get_private().clone(), public.clone()); 168 | let decrypted = ntru::decrypt(&encrypted, &kp_decrypt2, params).unwrap(); 169 | for i in 0..plain_len { 170 | assert_eq!(plain[i as usize], decrypted[i as usize]); 171 | } 172 | } 173 | } 174 | } 175 | 176 | 177 | // Tests ntru_encrypt() with a deterministic RNG 178 | fn test_encr_decr_det(params: &EncParams, digest_expected: &[u8]) { 179 | let kp = gen_key_pair("seed value for key generation", params); 180 | let pub_arr = kp.get_public().export(params); 181 | 182 | let pub2 = PublicKey::import(&pub_arr); 183 | assert_eq!(kp.get_public().get_h(), pub2.get_h()); 184 | 185 | let max_len = params.max_msg_len(); 186 | let rng_plaintext = RNG_CTR_DRBG; 187 | let plain_seed = b"seed value for plaintext"; 188 | 189 | let rand_ctx_plaintext = ntru::rand::init_det(&rng_plaintext, plain_seed).unwrap(); 190 | let plain = ntru::rand::generate(max_len as u16, &rand_ctx_plaintext).unwrap(); 191 | let plain2 = plain.clone(); 192 | 193 | let seed = b"seed value"; 194 | let seed2 = b"seed value"; 195 | 196 | let rng = RNG_CTR_DRBG; 197 | let rand_ctx = ntru::rand::init_det(&rng, seed).unwrap(); 198 | let rng2 = RNG_CTR_DRBG; 199 | let rand_ctx2 = ntru::rand::init_det(&rng2, seed2).unwrap(); 200 | 201 | for plain_len in 0..max_len as usize { 202 | let encrypted = ntru::encrypt(&plain[0..plain_len], kp.get_public(), params, &rand_ctx) 203 | .unwrap(); 204 | let encrypted2 = ntru::encrypt(&plain2[0..plain_len], &pub2, params, &rand_ctx2).unwrap(); 205 | 206 | for (i, c) in encrypted.iter().enumerate() { 207 | assert_eq!(*c, encrypted2[i]); 208 | } 209 | 210 | let decrypted = ntru::decrypt(&encrypted, &kp, params).unwrap(); 211 | 212 | for i in 0..plain_len { 213 | assert_eq!(plain[i], decrypted[i]); 214 | } 215 | } 216 | 217 | let encrypted = ntru::encrypt(&plain, kp.get_public(), params, &rand_ctx).unwrap(); 218 | let digest = sha1(&encrypted); 219 | assert_eq!(digest, digest_expected); 220 | } 221 | 222 | #[test] 223 | fn it_encr_decr() { 224 | let param_arr = ALL_PARAM_SETS; 225 | 226 | // SHA-1 digests of deterministic ciphertexts, one set for big-endian environments and one for 227 | // little-endian ones. If/when the CTR_DRBG implementation is made endian independent, only one 228 | // set of digests will be needed here. 229 | let digests_expected: [[u8; 20]; 18] = 230 | // EES401EP1 231 | [[0xdf, 0xad, 0xcd, 0x25, 0x01, 0x9f, 0x3d, 0xb1, 0x06, 0x5f, 232 | 0x15, 0xbe, 0x8f, 0x69, 0xfd, 0x23, 0x88, 0x88, 0x2a, 0xc8], 233 | // EES449EP1 234 | [0xc3, 0x8b, 0x8d, 0xdc, 0xfd, 0xef, 0xf8, 0x1b, 0xa6, 0x57, 235 | 0xeb, 0x66, 0x49, 0xe8, 0xe9, 0x4d, 0x70, 0xab, 0xce, 0x02], 236 | // EES677EP1 237 | [0xfd, 0xa8, 0xb1, 0xdb, 0x96, 0xc4, 0x3a, 0xeb, 0x0c, 0x07, 238 | 0xef, 0xf7, 0xc0, 0xf4, 0x73, 0x59, 0x6e, 0xd9, 0x97, 0xb7], 239 | // EES1087EP2 240 | [0xe7, 0x53, 0xd6, 0x89, 0xc6, 0x06, 0x3d, 0xf1, 0x12, 0xf1, 241 | 0xeb, 0x8b, 0xd8, 0x7c, 0x26, 0x67, 0xc9, 0xe5, 0x4a, 0x0e], 242 | // EES541EP1 243 | [0x7a, 0x5d, 0x41, 0x88, 0x70, 0xef, 0x4f, 0xf3, 0xdf, 0xb9, 244 | 0xa8, 0x76, 0x00, 0x00, 0x6d, 0x65, 0x61, 0xe0, 0xce, 0x44], 245 | // EES613EP1 246 | [0x69, 0x7b, 0x0a, 0x4f, 0xd6, 0x41, 0x04, 0x3f, 0x91, 0xe9, 247 | 0xb0, 0xa9, 0x42, 0xfe, 0x66, 0x4e, 0xcc, 0x4e, 0xbb, 0xd7], 248 | // EES887EP1 249 | [0xac, 0x3a, 0x51, 0xd6, 0xaf, 0x6c, 0x38, 0xa8, 0x67, 0xde, 250 | 0xc8, 0xfe, 0xf7, 0xaf, 0x4a, 0x28, 0x6e, 0x30, 0xad, 0x98], 251 | // EES1171EP1 252 | [0x5f, 0x34, 0x5f, 0xf7, 0x32, 0x13, 0x06, 0x55, 0x6b, 0xb7, 253 | 0x02, 0x7d, 0xb3, 0x16, 0xef, 0x84, 0x09, 0xe9, 0xa0, 0xff], 254 | // EES659EP1 255 | [0x2e, 0x35, 0xd4, 0xa6, 0x99, 0xb8, 0x5e, 0x06, 0x47, 0x61, 256 | 0x68, 0x20, 0x26, 0xb0, 0x17, 0xa9, 0xc6, 0x37, 0xb7, 0x8e], 257 | // EES761EP1 258 | [0x15, 0xde, 0x51, 0xbb, 0xc0, 0xe0, 0x39, 0xf2, 0xb6, 0x0e, 259 | 0x98, 0xa7, 0xae, 0x10, 0xbf, 0xfd, 0x02, 0xcc, 0x76, 0x43], 260 | // EES1087EP1 261 | [0x29, 0xac, 0x2d, 0x21, 0x29, 0x79, 0x98, 0x89, 0x1c, 0xa0, 262 | 0x6c, 0xed, 0x7d, 0x68, 0x29, 0x9b, 0xb4, 0x9f, 0xe4, 0xd0], 263 | // EES1499EP1 264 | [0x2f, 0xf9, 0x32, 0x25, 0xbc, 0xd5, 0xad, 0xc4, 0x4b, 0x19, 265 | 0xca, 0xe6, 0x52, 0x89, 0x2e, 0x29, 0x38, 0x5a, 0x61, 0xd7], 266 | // EES401EP2 267 | [0xaf, 0x39, 0x02, 0xd5, 0xaa, 0xab, 0x29, 0xaa, 0x01, 0x99, 268 | 0xd1, 0xf4, 0x0f, 0x02, 0x35, 0x58, 0x71, 0x58, 0xdb, 0xdb], 269 | // EES439EP1 270 | [0xa3, 0xd6, 0x5f, 0x7d, 0x5d, 0x66, 0x49, 0x1e, 0x15, 0xbc, 271 | 0xba, 0xf0, 0xfa, 0x07, 0x9d, 0xd3, 0x33, 0xf5, 0x9f, 0x37], 272 | // EES443EP1 273 | [0xac, 0xea, 0xa3, 0xc8, 0x05, 0x8b, 0x23, 0x68, 0xaa, 0x9a, 274 | 0x3c, 0x9b, 0xdb, 0x7f, 0xbe, 0x7b, 0x49, 0x03, 0x94, 0xc8], 275 | // EES593EP1 276 | [0x49, 0xfb, 0x90, 0x33, 0xaf, 0x12, 0xc7, 0x29, 0x17, 0x47, 277 | 0xf2, 0x09, 0xb9, 0xc3, 0x5d, 0xf4, 0x21, 0x5a, 0xbf, 0x98], 278 | // EES587EP1 279 | [0x69, 0xa8, 0x36, 0x3d, 0xe1, 0xec, 0x9e, 0x89, 0xa1, 0x0a, 280 | 0xa5, 0xb7, 0x35, 0xbe, 0x5b, 0x75, 0xb6, 0xd8, 0xe1, 0x9a], 281 | // EES743EP1 282 | [0x93, 0xfe, 0x81, 0xd5, 0x79, 0x2e, 0x34, 0xd8, 0xe3, 0x1f, 283 | 0xe5, 0x03, 0xb9, 0x06, 0xdc, 0x4f, 0x28, 0xb9, 0xaf, 0x37]]; 284 | 285 | for (i, param) in param_arr.iter().enumerate() { 286 | test_encr_decr_nondet(param); 287 | test_encr_decr_det(param, &digests_expected[i]); 288 | } 289 | } 290 | -------------------------------------------------------------------------------- /tests/poly.rs: -------------------------------------------------------------------------------- 1 | #![forbid(missing_docs, warnings)] 2 | #![deny(deprecated, improper_ctypes, non_shorthand_field_patterns, overflowing_literals, 3 | plugin_as_library, private_no_mangle_fns, private_no_mangle_statics, stable_features, 4 | unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation, 5 | unused_attributes, unused_comparisons, unused_features, unused_parens, while_true)] 6 | #![warn(trivial_casts, trivial_numeric_casts, unused, unused_extern_crates, unused_import_braces, 7 | unused_qualifications, unused_results, variant_size_differences)] 8 | 9 | #[macro_use] 10 | extern crate ntru; 11 | use ntru::types::{MAX_DEGREE, MAX_ONES, IntPoly, TernPoly, ProdPoly, PrivPoly}; 12 | use ntru::encparams::EES1087EP1; 13 | use ntru::rand::{RNG_DEFAULT, RandContext}; 14 | 15 | fn ntru_mult_int_nomod(a: &IntPoly, b: &IntPoly) -> IntPoly { 16 | if a.get_coeffs().len() != b.get_coeffs().len() { 17 | panic!("Incompatible int polys") 18 | } 19 | let n = a.get_coeffs().len(); 20 | 21 | let mut coeffs = Vec::with_capacity(n); 22 | for k in 0..n { 23 | let mut ck = 0i32; 24 | for i in 0..n { 25 | ck += b.get_coeffs()[i] as i32 * a.get_coeffs()[((n + k - i) % n)] as i32; 26 | } 27 | coeffs.push(ck as i16); 28 | } 29 | 30 | IntPoly::new(&coeffs[..]) 31 | } 32 | 33 | fn u8_arr_to_u16(arr: &[u8]) -> u16 { 34 | if arr.len() != 2 { 35 | panic!("u8_arr_to_u16() requires an array of 2 elements") 36 | } 37 | ((arr[0] as u16) << 8) + arr[1] as u16 38 | } 39 | 40 | fn ntru_priv_to_int(a: &PrivPoly, modulus: u16) -> IntPoly { 41 | if a.is_product() { 42 | a.get_poly_prod().to_int_poly(modulus) 43 | } else { 44 | a.get_poly_tern().to_int_poly() 45 | } 46 | } 47 | 48 | fn rand_int(n: u16, pow2q: u16, rand_ctx: &RandContext) -> IntPoly { 49 | let rand_data = rand_ctx.get_rng().generate(n * 2, rand_ctx).unwrap(); 50 | let shift = if pow2q < 16 { 51 | 16 - pow2q 52 | } else { 53 | u16::max_value() - pow2q + 16 54 | }; 55 | 56 | let mut coeffs = vec![0i16; n as usize]; 57 | for i in n..0 { 58 | coeffs[i as usize] = rand_data[i as usize] as i16 >> shift; 59 | } 60 | IntPoly::new(&coeffs.into_boxed_slice()) 61 | } 62 | 63 | fn verify_inverse(a: &PrivPoly, b: &IntPoly, modulus: u16) -> bool { 64 | let mut a_int = ntru_priv_to_int(a, modulus); 65 | a_int.mult_fac(3); 66 | let new_coeff = a_int.get_coeffs()[0] + 1; 67 | a_int.set_coeff(0, new_coeff); 68 | 69 | let (mut c, _) = a_int.mult_int(b, modulus - 1); 70 | c.mod_mask(modulus - 1); 71 | c.equals1() 72 | } 73 | 74 | #[test] 75 | fn it_mult_int() { 76 | // Multiplication modulo q 77 | let a1 = IntPoly::new(&[-1, 1, 1, 0, -1, 0, 1, 0, 0, 1, -1]); 78 | let b1 = IntPoly::new(&[14, 11, 26, 24, 14, 16, 30, 7, 25, 6, 19]); 79 | let (c1, _) = a1.mult_int(&b1, 32 - 1); 80 | 81 | let c1_exp = IntPoly::new(&[3, 25, -10, 21, 10, 7, 6, 7, 5, 29, -7]); 82 | assert!(c1_exp.equals_mod(&c1, 32)); 83 | 84 | // ntru_mult_mod should give the same result as ntru_mult_int_nomod followed by ntru_mod_mask 85 | let a2 = IntPoly::new(&[1278, 1451, 850, 1071, 942]); 86 | let b2 = IntPoly::new(&[571, 52, 1096, 1800, 662]); 87 | 88 | let (c2, _) = a2.mult_int(&b2, 2048 - 1); 89 | let mut c2_exp = ntru_mult_int_nomod(&a2, &b2); 90 | c2_exp.mod_mask(2048 - 1); 91 | 92 | assert!(c2_exp.equals_mod(&c2, 2048)); 93 | 94 | let rng = RNG_DEFAULT; 95 | let rand_ctx = ntru::rand::init(&rng).unwrap(); 96 | 97 | for _ in 0..10 { 98 | let n_arr = rand_ctx.get_rng().generate(2, &rand_ctx).unwrap(); 99 | let mut n = u8_arr_to_u16(&n_arr); 100 | n = 100 + (n % (MAX_DEGREE - 100) as u16); 101 | 102 | let a3 = IntPoly::rand(n, 11, &rand_ctx); 103 | let b3 = IntPoly::rand(n, 11, &rand_ctx); 104 | let mut c3_exp = ntru_mult_int_nomod(&a3, &b3); 105 | c3_exp.mod_mask(2048 - 1); 106 | 107 | let (c3, _) = a3.mult_int(&b3, 2048 - 1); 108 | assert!(c3_exp.equals_mod(&c3, 2048)); 109 | } 110 | } 111 | 112 | #[test] 113 | fn it_mult_tern() { 114 | let rng = RNG_DEFAULT; 115 | let rand_ctx = ntru::rand::init(&rng).unwrap(); 116 | 117 | let a = TernPoly::rand(11, 3, 3, &rand_ctx).unwrap(); 118 | let b = rand_int(11, 5, &rand_ctx); 119 | 120 | let a_int = a.to_int_poly(); 121 | let (c_int, _) = a_int.mult_int(&b, 32 - 1); 122 | let (c_tern, _) = b.mult_tern(&a, 32 - 1); 123 | 124 | assert!(c_tern.equals_mod(&c_int, 32)); 125 | 126 | for _ in 0..10 { 127 | let mut n = u8_arr_to_u16(&rand_ctx.get_rng().generate(2, &rand_ctx).unwrap()); 128 | n = 100 + (n % (MAX_DEGREE as u16 - 100)); 129 | let mut num_ones = u8_arr_to_u16(&rand_ctx.get_rng() 130 | .generate(2, &rand_ctx) 131 | .unwrap()); 132 | num_ones %= n / 2; 133 | num_ones %= MAX_ONES as u16; 134 | 135 | let mut num_neg_ones = u8_arr_to_u16(&rand_ctx.get_rng() 136 | .generate(2, &rand_ctx) 137 | .unwrap()); 138 | num_neg_ones %= n / 2; 139 | num_neg_ones %= MAX_ONES as u16; 140 | 141 | let a = TernPoly::rand(n, num_ones, num_neg_ones, &rand_ctx).unwrap(); 142 | let b = rand_int(n, 11, &rand_ctx); 143 | let a_int = a.to_int_poly(); 144 | 145 | let c_int = ntru_mult_int_nomod(&a_int, &b); 146 | let (c_tern, _) = b.mult_tern(&a, 2048 - 1); 147 | 148 | assert!(c_tern.equals_mod(&c_int, 2048)); 149 | } 150 | } 151 | 152 | #[test] 153 | fn it_mult_prod() { 154 | let rng = RNG_DEFAULT; 155 | let rand_ctx = ntru::rand::init(&rng).unwrap(); 156 | 157 | let log_modulus = 11u16; 158 | let modulus = 1 << log_modulus; 159 | 160 | for _ in 0..10 { 161 | let a = ProdPoly::rand(853, 8, 8, 8, 9, &rand_ctx).unwrap(); 162 | let b = rand_int(853, 1 << log_modulus, &rand_ctx); 163 | let (c_prod, _) = b.mult_prod(&a, modulus - 1); 164 | 165 | let a_int = a.to_int_poly(modulus); 166 | let (c_int, _) = a_int.mult_int(&b, modulus - 1); 167 | 168 | assert!(c_prod.equals_mod(&c_int, log_modulus)); 169 | } 170 | } 171 | 172 | #[test] 173 | fn it_inv() { 174 | let a1 = PrivPoly::new_with_tern_poly(TernPoly::new(11, &[1, 2, 6, 9], &[0, 3, 4, 10])); 175 | let (b1, invertible) = a1.invert(32 - 1); 176 | assert!(invertible); 177 | assert!(verify_inverse(&a1, &b1, 32)); 178 | 179 | // Test 3 random polynomials 180 | let mut num_invertible = 0u16; 181 | let rng = RNG_DEFAULT; 182 | let rand_ctx = ntru::rand::init(&rng).unwrap(); 183 | 184 | while num_invertible < 3 { 185 | let a2 = PrivPoly::new_with_tern_poly(TernPoly::rand(853, 100, 100, &rand_ctx).unwrap()); 186 | let (b, invertible) = a2.invert(2048 - 1); 187 | 188 | if invertible { 189 | assert!(verify_inverse(&a2, &b, 2048)); 190 | num_invertible += 1; 191 | } 192 | } 193 | 194 | // #ifdef NTRU_AVOID_HAMMING_WT_PATENT 195 | num_invertible = 0; 196 | while num_invertible < 3 { 197 | let a3 = PrivPoly::new_with_tern_poly(TernPoly::rand(853, 100, 100, &rand_ctx).unwrap()); 198 | let (b, invertible) = a3.invert(2048 - 1); 199 | 200 | if invertible { 201 | assert!(verify_inverse(&a3, &b, 2048)); 202 | num_invertible += 1; 203 | } 204 | } 205 | // #endif 206 | 207 | // test a non-invertible polynomial 208 | let a2 = PrivPoly::new_with_tern_poly(TernPoly::new(11, &[3, 10], &[0, 6, 8])); 209 | let (_, invertible) = a2.invert(32 - 1); 210 | assert!(!invertible); 211 | } 212 | 213 | #[test] 214 | fn it_arr() { 215 | let params = EES1087EP1; 216 | let rng = RNG_DEFAULT; 217 | let rand_ctx = ntru::rand::init(&rng).unwrap(); 218 | let p1 = rand_int(params.get_n(), 11, &rand_ctx); 219 | let a = p1.to_arr(¶ms); 220 | 221 | let p2 = IntPoly::from_arr(&a, params.get_n(), params.get_q()); 222 | 223 | assert_eq!(p1, p2); 224 | } 225 | --------------------------------------------------------------------------------