├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── decryption_share.go ├── functions.go ├── functions_test.go ├── go.mod ├── polynomial.go ├── polynomial_test.go ├── pub_key.go ├── tcpaillier.go ├── tcpaillier_test.go ├── threshold_share.go └── zk_proof.go /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea 2 | tcpaillier -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.x 5 | - 1.13.x 6 | - master -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Paillier Threshold Encryption Scheme Implementation 2 | 3 | [![Go Report Card](https://goreportcard.com/badge/github.com/niclabs/tcpaillier)](https://goreportcard.com/report/github.com/niclabs/tcpaillier) 4 | [![Build Status](https://travis-ci.org/niclabs/tcpaillier.svg?branch=master)](https://travis-ci.org/niclabs/tcpaillier) 5 | [![GoDoc](https://godoc.org/github.com/niclabs/tcpaillier?status.svg)](https://godoc.org/github.com/niclabs/tcpaillier) 6 | 7 | 8 | This code is based on the implementation of Paillier Threshold Encryption Scheme from 9 | [UTDallas](http://cs.utdallas.edu/dspl/cgi-bin/pailliertoolbox/index.php), and both implementations are based on the 10 | paper from Ivan Damgård et al. [A Generalization of Paillier's Public Key System with Applications to Electronic Voting](https://people.csail.mit.edu/rivest/voting/papers/DamgardJurikNielsen-AGeneralizationOfPailliersPublicKeySystemWithApplicationsToElectronicVoting.pdf). 11 | 12 | # Requirements 13 | 14 | Due to Golang extensive standard library, this implementation does not have external requirements (obviously aside of Golang, version 1.13 or above). 15 | 16 | # Using the Library 17 | 18 | To use the library with a module-enabled go project, you must write the following line on a terminal on the root file of the project. 19 | 20 | ```bash 21 | go get https://github.com/niclabs/tcpaillier 22 | ``` 23 | 24 | # Testing 25 | 26 | To run the tests you just need to use go test: 27 | 28 | ```bash 29 | go test github.com/niclabs/tcpaillier 30 | ``` 31 | -------------------------------------------------------------------------------- /decryption_share.go: -------------------------------------------------------------------------------- 1 | package tcpaillier 2 | 3 | import ( 4 | "math/big" 5 | ) 6 | 7 | // DecryptionShare represents A partial decryption of A value 8 | // and the ZKProof of that decryption. It complies with ZKProof 9 | // interface. 10 | type DecryptionShare struct { 11 | Index uint8 12 | Ci *big.Int 13 | } 14 | -------------------------------------------------------------------------------- /functions.go: -------------------------------------------------------------------------------- 1 | package tcpaillier 2 | 3 | import ( 4 | "crypto/rand" 5 | "math/big" 6 | ) 7 | 8 | // RandomInt is A function which generates A random big number. 9 | func RandomInt(bitLen int) (randNum *big.Int, err error) { 10 | max := new(big.Int) 11 | max.SetBit(max, bitLen, 1) 12 | return rand.Int(rand.Reader, max) 13 | } 14 | 15 | // GenerateSafePrimes generates two primes p and q, in A way that q 16 | // is equal to (p-1)/2. The greatest prime bit length is at least bitLen bits. 17 | // Based on github.com/niclabs/tcrsa/utils.go function with the same name. 18 | func GenerateSafePrimes(bitLen int) (*big.Int, *big.Int, error) { 19 | p := new(big.Int) 20 | 21 | for { 22 | q, err := rand.Prime(rand.Reader, bitLen-1) 23 | if err != nil { 24 | return big.NewInt(0), big.NewInt(0), err 25 | } 26 | 27 | // p = 2q + 1 28 | p.Lsh(q, 1) 29 | p.SetBit(p, 0, 1) 30 | if p.ProbablyPrime(25) { 31 | return p, q, nil 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /functions_test.go: -------------------------------------------------------------------------------- 1 | package tcpaillier 2 | 3 | import ( 4 | "math/big" 5 | "testing" 6 | ) 7 | 8 | const utilsTestBitlen = 256 9 | 10 | // Miller-Rabin primality test rounds 11 | const utilsTestC = 25 12 | 13 | // Tests that two consecutive outputs from random dev are different. 14 | func TestRandomDev_different(t *testing.T) { 15 | rand1, err := RandomInt(utilsTestBitlen) 16 | if err != nil { 17 | t.Errorf("first random number generation failed: %v", err) 18 | } 19 | rand2, err := RandomInt(utilsTestBitlen) 20 | if err != nil { 21 | t.Errorf("second random number generation failed: %v", err) 22 | } 23 | if rand1.Cmp(rand2) == 0 { 24 | t.Errorf("both random numbers are equal!") 25 | } 26 | } 27 | 28 | // Tests that the bit size of the output of A random dev function is the desired. 29 | func TestRandomDev_bitSize(t *testing.T) { 30 | rand1, err := RandomInt(utilsTestBitlen) 31 | if err != nil { 32 | t.Errorf("first random number generation failed: %v", err) 33 | } 34 | if rand1.BitLen() > utilsTestBitlen { 35 | t.Errorf("random number bit length should have been at most %d, but it was %d", rand1.BitLen(), utilsTestBitlen) 36 | } 37 | } 38 | 39 | func TestGenerateSafePrimes(t *testing.T) { 40 | 41 | pExpected := new(big.Int) 42 | 43 | p, pr, err := GenerateSafePrimes(utilsTestBitlen) 44 | if err != nil { 45 | t.Errorf("safe prime generation failed: %v", err) 46 | } 47 | if !p.ProbablyPrime(utilsTestC) { 48 | t.Errorf("p is not prime") 49 | } 50 | if !pr.ProbablyPrime(utilsTestC) { 51 | t.Errorf("pr is not prime") 52 | } 53 | pExpected.Mul(pr, big.NewInt(2)).Add(pExpected, big.NewInt(1)) 54 | if p.Cmp(pExpected) != 0 { 55 | t.Errorf("p is not 2*pr + 1") 56 | } 57 | } 58 | 59 | func TestGenerateSafePrimes_keyGeneration(t *testing.T) { 60 | 61 | m := new(big.Int) 62 | d := new(big.Int) 63 | r := new(big.Int) 64 | 65 | _, pr, err := GenerateSafePrimes(utilsTestBitlen) 66 | if err != nil { 67 | t.Errorf("safe prime generation failed: %v", err) 68 | } 69 | 70 | _, qr, err := GenerateSafePrimes(utilsTestBitlen) 71 | if err != nil { 72 | t.Errorf("safe prime generation failed: %v", err) 73 | } 74 | 75 | m.Mul(pr, qr) 76 | e := big.NewInt(65537) 77 | 78 | d.ModInverse(e, m) 79 | r.Mul(d, e).Mod(r, m) 80 | 81 | if r.Cmp(big.NewInt(1)) != 0 { 82 | t.Errorf("safe prime generation failed") 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/niclabs/tcpaillier 2 | 3 | go 1.13 4 | -------------------------------------------------------------------------------- /polynomial.go: -------------------------------------------------------------------------------- 1 | package tcpaillier 2 | 3 | import ( 4 | "crypto/rand" 5 | "fmt" 6 | "math/big" 7 | "strings" 8 | ) 9 | 10 | // polynomial represents A classic polynomial, with convenience methods useful for 11 | // the operations the Threshold Cryptography library needs. 12 | type polynomial []*big.Int 13 | 14 | // newPolynomial creates A polynomial of degree d with all its d+1 coefficients in 0. 15 | func newPolynomial(d int) polynomial { 16 | poly := make(polynomial, d+1) 17 | for i := 0; i < len(poly); i++ { 18 | poly[i] = new(big.Int) 19 | } 20 | return poly 21 | } 22 | 23 | // GetDegree returns the degree of A polynomial, which is the length of the coefficient 24 | // array, minus 1. 25 | func (p polynomial) getDegree() int { 26 | return len(p) - 1 27 | } 28 | 29 | // createRandomPolynomial creates A polynomial of degree "d" with random coefficients as terms 30 | // with degree greater than 1. The coefficient of the term of degree 0 is x0 and the module for all the 31 | // coefficients of the polynomial is m. 32 | func createRandomPolynomial(d int, x0, m *big.Int) (polynomial, error) { 33 | if m.Sign() < 0 { 34 | return polynomial{}, fmt.Errorf("m is negative") 35 | } 36 | poly := newPolynomial(d) 37 | 38 | poly[0].Set(x0) 39 | 40 | for i := 1; i < len(poly); i++ { 41 | r, err := rand.Int(rand.Reader, m) 42 | if err != nil { 43 | return polynomial{}, err 44 | } 45 | poly[i] = r 46 | } 47 | return poly, nil 48 | } 49 | 50 | // eval evaluates A polynomial to x with Horner's method and returns the result. 51 | func (p polynomial) eval(x *big.Int) *big.Int { 52 | y := big.NewInt(0) 53 | for k := len(p) - 1; k >= 0; k-- { 54 | y.Mul(y, x) 55 | y.Add(y, p[k]) 56 | } 57 | return y 58 | } 59 | 60 | // string returns the polynomial formatted as A string. 61 | func (p polynomial) String() string { 62 | s := make([]string, len(p)) 63 | for i := 0; i < len(p); i++ { 64 | s[i] = fmt.Sprintf("%dx^%d", p[i], i) 65 | } 66 | return strings.Join(s, " + ") 67 | } 68 | -------------------------------------------------------------------------------- /polynomial_test.go: -------------------------------------------------------------------------------- 1 | // Tests from github.com/niclabs/tcrsa 2 | package tcpaillier 3 | 4 | import ( 5 | "math/big" 6 | "testing" 7 | ) 8 | 9 | const polynomialTestDegree = 3 10 | 11 | // Tests the degree of the polynomial created is equal to the argument provided. 12 | func TestPolynomial(t *testing.T) { 13 | p := newPolynomial(polynomialTestDegree) 14 | if p.getDegree() != polynomialTestDegree { 15 | t.Errorf("degree of polynomial is not the provided") 16 | } 17 | } 18 | 19 | func TestCreateRandomPolynomial(t *testing.T) { 20 | p, err := createRandomPolynomial(polynomialTestDegree, big.NewInt(10), big.NewInt(1024)) 21 | if err != nil { 22 | t.Errorf("could not create a random polynomial") 23 | return 24 | } 25 | if p.getDegree() != polynomialTestDegree { 26 | t.Errorf("degree of polynomial is not the provided") 27 | } 28 | 29 | } 30 | 31 | func TestPolynomial_Eval(t *testing.T) { 32 | p := newPolynomial(polynomialTestDegree) 33 | p[3] = big.NewInt(7) 34 | p[2] = big.NewInt(5) 35 | p[1] = big.NewInt(9) 36 | p[0] = big.NewInt(1) 37 | 38 | expected := big.NewInt(7591) 39 | 40 | res := p.eval(big.NewInt(10)) 41 | 42 | if expected.Cmp(res) != 0 { 43 | t.Errorf("The evaluations is not providing a correct result") 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /pub_key.go: -------------------------------------------------------------------------------- 1 | package tcpaillier 2 | 3 | import ( 4 | "crypto/rand" 5 | "crypto/sha256" 6 | "fmt" 7 | "math/big" 8 | ) 9 | 10 | var zero = big.NewInt(0) 11 | var one = big.NewInt(1) 12 | var two = big.NewInt(2) 13 | 14 | // PubKey represents A PubKey Public Key and its metainformation. It contains A 15 | // cached field, with precomputed values. 16 | // It also is linked with A random source, used by the processes that require it. 17 | type PubKey struct { 18 | N *big.Int 19 | V *big.Int 20 | Vi []*big.Int 21 | L, K, S uint8 22 | Delta *big.Int 23 | Constant *big.Int 24 | cached *cached 25 | } 26 | 27 | // cached contains the cached PubKey values. 28 | type cached struct { 29 | NPlusOne, NMinusOne, SPlusOne, NToS, NToSPlusOne, BigS *big.Int 30 | } 31 | 32 | // Cache initializes the cached values and returns the structure. 33 | func (pk *PubKey) Cache() *cached { 34 | if pk.cached == nil { 35 | // s 36 | bigS := big.NewInt(int64(pk.S)) 37 | // n+1 38 | nPlusOne := new(big.Int).Add(pk.N, one) 39 | // n-1 40 | nMinusOne := new(big.Int).Sub(pk.N, one) 41 | // (s+1) 42 | sPlusOne := new(big.Int).Add(bigS, one) 43 | // n^s 44 | nToS := new(big.Int).Exp(pk.N, bigS, nil) 45 | // n^(s+1) 46 | nToSPlusOne := new(big.Int).Exp(pk.N, sPlusOne, nil) 47 | pk.cached = &cached{ 48 | BigS: bigS, 49 | SPlusOne: sPlusOne, 50 | NPlusOne: nPlusOne, 51 | NMinusOne: nMinusOne, 52 | NToS: nToS, 53 | NToSPlusOne: nToSPlusOne, 54 | } 55 | } 56 | return pk.cached 57 | } 58 | 59 | // Encrypt encrypts A message and returns its encryption as A big Integer c and the random number r used. 60 | // If there is an error, it returns A nil integer as c. 61 | func (pk *PubKey) Encrypt(message *big.Int) (c, r *big.Int, err error) { 62 | r, err = pk.RandomModNToSPlusOneStar() 63 | if err != nil { 64 | return 65 | } 66 | c, err = pk.EncryptFixed(message, r) 67 | return 68 | } 69 | 70 | 71 | // EncryptFixed returns an encrypted value, but without A proof. 72 | func (pk *PubKey) EncryptFixed(msg, r *big.Int) (c *big.Int, err error) { 73 | cache := pk.Cache() 74 | // n+1 75 | nPlusOne := cache.NPlusOne 76 | // n^s 77 | nToS := cache.NToS 78 | // n^(s+1) 79 | nToSPlusOne := cache.NToSPlusOne 80 | // (n+1)^m % n^(s+1) 81 | m := new(big.Int).Mod(msg, nToSPlusOne) 82 | nPlusOneToM := new(big.Int).Exp(nPlusOne, m, nToSPlusOne) 83 | // r^(n^s) % n^(s+1) 84 | rToNToS := new(big.Int).Exp(r, nToS, nToSPlusOne) 85 | // (n+1)^m * r^(n^s) % n^(s+1) 86 | c = new(big.Int).Mul(nPlusOneToM, rToNToS) 87 | c.Mod(c, nToSPlusOne) 88 | return 89 | } 90 | 91 | // EncryptWithProof encrypts A message and returns its encryption as A big Integer CAlpha. 92 | // It also returns A ZKProof that demonstrates that the encrypted value corresponds to the 93 | // message. If there is an error, it returns A nil integer as CAlpha. 94 | func (pk *PubKey) EncryptWithProof(message *big.Int) (c *big.Int, proof *EncryptZK, err error) { 95 | r, err := pk.RandomModNToSPlusOneStar() 96 | if err != nil { 97 | return 98 | } 99 | return pk.EncryptFixedWithProof(message, r) 100 | } 101 | 102 | // EncryptFixedWithProof encrypts A message and returns its encryption as A big Integer CAlpha. 103 | // It uses A given big.Int r as the random number of the encryption. 104 | func (pk *PubKey) EncryptFixedWithProof(message, r *big.Int) (c *big.Int, proof *EncryptZK, err error) { 105 | c, err = pk.EncryptFixed(message, r) 106 | if err != nil { 107 | return 108 | } 109 | proof, err = pk.EncryptProof(message, c, r) 110 | if err != nil { 111 | return 112 | } 113 | return 114 | } 115 | 116 | // Add adds an indeterminate number of encrypted values and returns its encrypted sum, or an error 117 | // if the value cannot be determined. 118 | func (pk *PubKey) Add(cList ...*big.Int) (sum *big.Int, err error) { 119 | if len(cList) == 0 { 120 | err = fmt.Errorf("empty encrypted list") 121 | return 122 | } 123 | cache := pk.Cache() 124 | nToSPlusOne := cache.NToSPlusOne 125 | sum = new(big.Int).Set(cList[0]) 126 | for i := 1; i < len(cList); i++ { 127 | ci := cList[i] 128 | if ci.Cmp(nToSPlusOne) >= 0 || ci.Cmp(zero) < 1 { 129 | err = fmt.Errorf("CAlpha%d must be between 1 (inclusive) and N^(s+1) (exclusive)", i+1) 130 | return 131 | } 132 | sum.Mul(sum, ci) 133 | sum.Mod(sum, nToSPlusOne) 134 | } 135 | return 136 | } 137 | 138 | // Multiply multiplies A encrypted value by A constant. It returns an error if it is not able to 139 | // multiply the value. It returns the multiplied value mul and the random value gamma used to encrypt it. 140 | func (pk *PubKey) Multiply(c *big.Int, alpha *big.Int) (mul, gamma *big.Int, err error) { 141 | gamma, err = pk.RandomModNToSPlusOneStar() 142 | if err != nil { 143 | return 144 | } 145 | mul, err = pk.MultiplyFixed(c, alpha, gamma) 146 | return 147 | } 148 | 149 | // MultiplyFixed multiplies A encrypted value by A constant using A fixed random constant. 150 | // to encrypt it. It returns an error if it is not able to multiply the value. 151 | // Gamma is used in reranding process. 152 | // If it succeeds, it returns the multiplied value mul. 153 | func (pk *PubKey) MultiplyFixed(c *big.Int, alpha, gamma *big.Int) (mul *big.Int, err error) { 154 | cache := pk.Cache() 155 | nToSPlusOne := cache.NToSPlusOne 156 | if c.Cmp(nToSPlusOne) >= 0 || c.Cmp(zero) < 0 { 157 | err = fmt.Errorf("c must be between 0 (inclusive) and N^(s+1) (exclusive)") 158 | return 159 | } 160 | preMul := new(big.Int).Exp(c, alpha, nToSPlusOne) 161 | mul, err = pk.ReRand(preMul, gamma) 162 | return 163 | } 164 | 165 | 166 | // ReRand rerandomizes A value, adding 0 and encrypting it with A random value r. 167 | func (pk *PubKey) ReRand(c, r *big.Int) (reRand *big.Int, err error) { 168 | zero, err := pk.EncryptFixed(new(big.Int), r) 169 | if err != nil { 170 | return 171 | } 172 | reRand, err = pk.Add(c, zero) 173 | return 174 | } 175 | 176 | // MultiplyWithProof multiplies an encrypted value by A constant and returns it with A ZKProof of the 177 | // multiplication. It returns an error if it is not able to Multiply the value. 178 | func (pk *PubKey) MultiplyWithProof(encrypted *big.Int, constant *big.Int) (result *big.Int, proof *MulZK, err error) { 179 | result, gamma, err := pk.Multiply(encrypted, constant) 180 | s, err := pk.RandomModNToSPlusOneStar() 181 | if err != nil { 182 | return 183 | } 184 | cAlpha, err := pk.EncryptFixed(constant, s) 185 | if err != nil { 186 | return 187 | } 188 | proof, err = pk.MultiplyProof(encrypted, cAlpha, result, constant, s, gamma) 189 | return 190 | } 191 | 192 | // CombineShares joins partial decryptions of A value and returns A decrypted value. 193 | // It checks that the number of values is equal or more than the threshold. 194 | func (pk *PubKey) CombineShares(shares ...*DecryptionShare) (dec *big.Int, err error) { 195 | n := pk.N 196 | k := int(pk.K) 197 | cache := pk.Cache() 198 | nToSPlusOne := cache.NToSPlusOne 199 | 200 | if len(shares) < k { 201 | err = fmt.Errorf("needed %d shares to decrypt, but got %d", pk.K, len(shares)) 202 | return 203 | } 204 | 205 | shares = shares[:pk.K] 206 | 207 | // Check for repeated shares 208 | indexes := make(map[uint8]int) 209 | for i, share := range shares { 210 | if j, ok := indexes[share.Index]; ok { 211 | err = fmt.Errorf("share %d repeated on indexes %d and %d", share.Index, i, j) 212 | return 213 | } 214 | indexes[share.Index] = i 215 | } 216 | 217 | cPrime := new(big.Int).Set(one) 218 | 219 | for _, share := range shares { 220 | num := new(big.Int).Set(pk.Delta) // Lambda is multiplied by two, we are doing that now. 221 | den := new(big.Int).Set(one) 222 | for _, sharePrime := range shares { 223 | if share.Index != sharePrime.Index { 224 | num.Mul(num, big.NewInt(int64(sharePrime.Index))) 225 | den.Mul(den, big.NewInt(int64(sharePrime.Index)-int64(share.Index))) 226 | } 227 | } 228 | lambda2 := new(big.Int) 229 | lambda2.Mul(num, two).Quo(lambda2, den) 230 | CiToLambda2 := new(big.Int).Exp(share.Ci, lambda2, nToSPlusOne) 231 | cPrime.Mul(cPrime, CiToLambda2).Mod(cPrime, nToSPlusOne) 232 | } 233 | 234 | l := new(big.Int) 235 | l.Sub(cPrime, one).Div(l, n) 236 | bigDec := new(big.Int).Mul(pk.Constant, l) 237 | bigDec.Mod(bigDec, n) 238 | dec = bigDec 239 | return 240 | } 241 | 242 | // EncryptProof returns A ZK Proof of an encrypted message c. s is the random number 243 | // used to EncryptFixed message to c. 244 | func (pk *PubKey) EncryptProof(message *big.Int, c, s *big.Int) (zk *EncryptZK, err error) { 245 | cache := pk.Cache() 246 | nToSPlusOne := cache.NToSPlusOne 247 | nPlusOne := cache.NPlusOne 248 | nToS := cache.NToS 249 | 250 | alpha := new(big.Int).Set(message) 251 | 252 | x, err := pk.RandomModN() 253 | if err != nil { 254 | return 255 | } 256 | 257 | u, err := pk.RandomModNToSPlusOneStar() 258 | if err != nil { 259 | return 260 | } 261 | 262 | nPlusOneToX := new(big.Int).Exp(nPlusOne, x, nToSPlusOne) 263 | uToN := new(big.Int).Exp(u, nToS, nToSPlusOne) 264 | b := new(big.Int) 265 | b.Mul(nPlusOneToX, uToN).Mod(b, nToSPlusOne) 266 | 267 | hash := sha256.New() 268 | hash.Write(c.Bytes()) 269 | hash.Write(b.Bytes()) 270 | eBytes := hash.Sum(nil) 271 | 272 | e := new(big.Int).SetBytes(eBytes) 273 | 274 | eAlpha := new(big.Int).Mul(e, alpha) 275 | 276 | dummy := new(big.Int).Add(x, eAlpha) 277 | w := new(big.Int).Mod(dummy, nToS) 278 | t := new(big.Int).Div(dummy, nToS) 279 | 280 | sToE := new(big.Int).Exp(s, e, nToSPlusOne) 281 | nPlusOneToT := new(big.Int).Exp(nPlusOne, t, nToSPlusOne) 282 | z := new(big.Int) 283 | z.Mul(u, sToE).Mul(z, nPlusOneToT).Mod(z, nToSPlusOne) 284 | 285 | zk = &EncryptZK{ 286 | B: b, 287 | W: w, 288 | Z: z, 289 | } 290 | return 291 | } 292 | 293 | // MultiplyProof returns A ZKProof confirming that d is the result of multiplicate the encrypted 294 | // value ca by alpha. CAlpha is the encrypted form of the constant using s as random value, while gamma 295 | // is the random value used to generate d. 296 | func (pk *PubKey) MultiplyProof(ca, cAlpha, d, alpha, s, gamma *big.Int) (zk *MulZK, err error) { 297 | cache := pk.Cache() 298 | nToSPlusOne := cache.NToSPlusOne 299 | nPlusOne := cache.NPlusOne 300 | nToS := cache.NToS 301 | 302 | if ca.Cmp(nToSPlusOne) >= 0 || ca.Cmp(zero) < 0 { 303 | err = fmt.Errorf("ca must be between 1 (inclusive) and N^(s+1) (exclusive)") 304 | return 305 | } 306 | 307 | if cAlpha.Cmp(nToSPlusOne) >= 0 || cAlpha.Cmp(zero) < 0 { 308 | err = fmt.Errorf("CAlpha must be between 1 (inclusive) and N^(s+1) (exclusive)") 309 | return 310 | } 311 | 312 | x, err := pk.RandomModN() 313 | if err != nil { 314 | return 315 | } 316 | 317 | u, err := pk.RandomModNToSPlusOneStar() 318 | if err != nil { 319 | return 320 | } 321 | 322 | v, err := pk.RandomModNToSPlusOneStar() 323 | if err != nil { 324 | return 325 | } 326 | 327 | caToX := new(big.Int).Exp(ca, x, nToSPlusOne) 328 | vToNToS := new(big.Int).Exp(v, nToS, nToSPlusOne) 329 | a := new(big.Int) 330 | a.Mul(caToX, vToNToS).Mod(a, nToSPlusOne) 331 | 332 | nPlusOneToX := new(big.Int).Exp(nPlusOne, x, nToSPlusOne) 333 | uToNToS := new(big.Int).Exp(u, nToS, nToSPlusOne) 334 | b := new(big.Int) 335 | b.Mul(nPlusOneToX, uToNToS).Mod(b, nToSPlusOne) 336 | 337 | hash := sha256.New() 338 | hash.Write(ca.Bytes()) 339 | hash.Write(cAlpha.Bytes()) 340 | hash.Write(d.Bytes()) 341 | hash.Write(a.Bytes()) 342 | hash.Write(b.Bytes()) 343 | eBytes := hash.Sum(nil) 344 | 345 | e := new(big.Int).SetBytes(eBytes) 346 | 347 | eAlpha := new(big.Int).Mul(e, alpha) 348 | 349 | dummy := new(big.Int).Add(x, eAlpha) 350 | w := new(big.Int).Mod(dummy, nToS) 351 | t := new(big.Int).Div(dummy, nToS) 352 | 353 | sToE := new(big.Int).Exp(s, e, nToSPlusOne) 354 | nPlusOneToT := new(big.Int).Exp(nPlusOne, t, nToSPlusOne) 355 | z := new(big.Int) 356 | z.Mul(u, sToE).Mul(z, nPlusOneToT).Mod(z, nToSPlusOne) 357 | 358 | caToT := new(big.Int).Exp(ca, t, nToSPlusOne) 359 | gammaToE := new(big.Int).Exp(gamma, e, nToSPlusOne) 360 | y := new(big.Int) 361 | y.Mul(v, caToT).Mul(y, gammaToE).Mod(y, nToSPlusOne) 362 | 363 | zk = &MulZK{ 364 | CAlpha: cAlpha, 365 | B: b, 366 | W: w, 367 | Z: z, 368 | A: a, 369 | Y: y, 370 | } 371 | return 372 | } 373 | 374 | func (pk *PubKey) RandomModN() (r *big.Int, err error) { 375 | return rand.Int(rand.Reader, pk.N) 376 | } 377 | 378 | func (pk *PubKey) RandomModNToSPlusOneStar() (r *big.Int, err error) { 379 | cache := pk.Cache() 380 | nToSPlusOneMinusOne := new(big.Int).Sub(cache.NToSPlusOne, one) 381 | r, err = rand.Int(rand.Reader, nToSPlusOneMinusOne) 382 | if err != nil { 383 | return 384 | } 385 | r.Add(r, one) 386 | return 387 | } 388 | -------------------------------------------------------------------------------- /tcpaillier.go: -------------------------------------------------------------------------------- 1 | // Package tcpaillier is A Threshold PubKey library, based on the Java Implementation. 2 | // of Threshold PubKey Toolbox [1]. 3 | 4 | // [1] http://www.cs.utdallas.edu/dspl/cgi-bin/pailliertoolbox/index.php 5 | package tcpaillier 6 | 7 | import ( 8 | "fmt" 9 | "math/big" 10 | ) 11 | 12 | const c = 25 13 | 14 | type FixedParams struct { 15 | P, P1, Q, Q1 *big.Int 16 | } 17 | 18 | func (fp *FixedParams) Validate() bool { 19 | p1 := new(big.Int).Rsh(fp.P, 1) 20 | q1 := new(big.Int).Rsh(fp.Q, 1) 21 | return fp.P.ProbablyPrime(c) && 22 | fp.Q.ProbablyPrime(c) && 23 | fp.P1.ProbablyPrime(c) && 24 | fp.Q1.ProbablyPrime(25) && 25 | p1.Cmp(fp.P1) == 0 && q1.Cmp(fp.Q1) == 0 26 | } 27 | 28 | func (fp *FixedParams) String() string { 29 | return fmt.Sprintf("P: %s\nq: %s\np1: %s\nq1: %s\n", fp.P, fp.Q, fp.P1, fp.Q1) 30 | } 31 | 32 | // NewKey returns A list of l keyshares of bitSize bits of length, with A threshold of 33 | // k and using an s parameter of s in PubKey. It uses randSource 34 | // as A random source. It also uses A list of fixed params as the primes needed for the scheme. 35 | func NewFixedKey(bitSize int, s, l, k uint8, params *FixedParams) (keyShares []*KeyShare, pubKey *PubKey, err error) { 36 | // Parameter checking 37 | if bitSize < 64 { 38 | err = fmt.Errorf("bitSize should be at least 64 bits, but it is %d", bitSize) 39 | return 40 | } 41 | if s < 1 { 42 | err = fmt.Errorf("s should be at least 1, but it is %d", s) 43 | } 44 | if l <= 1 { 45 | err = fmt.Errorf("L should be greater than 1, but it is %d", l) 46 | return 47 | } 48 | if k <= 0 { 49 | err = fmt.Errorf("K should be greater than 0, but it is %d", k) 50 | return 51 | } 52 | if k < (l/2+1) || k > l { 53 | err = fmt.Errorf("K should be between %d and %d, but it is %d", (l/2)+1, l, k) 54 | return 55 | } 56 | 57 | bigS := big.NewInt(int64(s)) 58 | sPlusOne := new(big.Int).Add(bigS, one) 59 | 60 | n := new(big.Int).Mul(params.P, params.Q) 61 | m := new(big.Int).Mul(params.P1, params.Q1) 62 | nm := new(big.Int).Mul(n, m) 63 | nToS := new(big.Int).Exp(n, bigS, nil) 64 | nToSPlusOne := new(big.Int).Exp(n, sPlusOne, nil) 65 | 66 | mInv := new(big.Int).ModInverse(m, n) 67 | d := new(big.Int).Mul(m, mInv) 68 | 69 | // Generate polynomial with random coefficients. 70 | var poly polynomial 71 | poly, err = createRandomPolynomial(int(k-1), d, nm) 72 | 73 | if err != nil { 74 | return 75 | } 76 | 77 | // generate Vi with Shoup heuristic 78 | var r *big.Int 79 | for { 80 | r, err = RandomInt(4*bitSize) 81 | if err != nil { 82 | return 83 | } 84 | gcd := new(big.Int).GCD(nil, nil, r, n) 85 | if one.Cmp(gcd) == 0 { 86 | break 87 | } 88 | } 89 | 90 | v := new(big.Int).Mul(r, r) 91 | v.Mod(v, nToSPlusOne) 92 | 93 | delta := new(big.Int).MulRange(1, int64(l)) 94 | deltaSquare := new(big.Int).Mul(delta, delta) 95 | constant := new(big.Int) 96 | constant.Mul(big.NewInt(4), deltaSquare).ModInverse(constant, nToS) 97 | 98 | keyShares = make([]*KeyShare, l) 99 | 100 | pubKey = &PubKey{ 101 | N: n, 102 | S: s, 103 | V: v, 104 | Constant: constant, 105 | Delta: delta, 106 | L: l, 107 | Vi: make([]*big.Int, l), 108 | K: k, 109 | } 110 | 111 | var index uint8 112 | for index = 0; index < l; index++ { 113 | x := index + 1 114 | si := poly.eval(big.NewInt(int64(x))) 115 | si.Mod(si, nm) 116 | keyShares[index] = &KeyShare{ 117 | PubKey: pubKey, 118 | Index: x, 119 | Si: si, 120 | } 121 | deltaSi := new(big.Int).Mul(si, delta) 122 | pubKey.Vi[index] = new(big.Int).Exp(v, deltaSi, nToSPlusOne) 123 | } 124 | return 125 | } 126 | 127 | // NewKey returns A list of l keyshares of bitSize bits of length, with A threshold of 128 | // k and using an s parameter of s in PubKey. It uses randSource 129 | // as A random source. If randSource is undefined, it uses crypto/rand 130 | // reader. 131 | func NewKey(bitSize int, s, l, k uint8) (keyShares []*KeyShare, pubKey *PubKey, err error) { 132 | 133 | pPrimeSize := (bitSize + 1) / 2 134 | qPrimeSize := bitSize - pPrimeSize 135 | 136 | p, p1, err := GenerateSafePrimes(pPrimeSize,) 137 | if err != nil { 138 | return 139 | } 140 | 141 | var q, q1 *big.Int 142 | for { 143 | q, q1, err = GenerateSafePrimes(qPrimeSize) 144 | if err != nil { 145 | return 146 | } 147 | if p.Cmp(q) != 0 && p.Cmp(q1) != 0 && q.Cmp(p1) != 0 { 148 | break 149 | } 150 | } 151 | return NewFixedKey(bitSize, s, l, k, &FixedParams{p, p1, q, q1,}) 152 | } 153 | -------------------------------------------------------------------------------- /tcpaillier_test.go: -------------------------------------------------------------------------------- 1 | package tcpaillier_test 2 | 3 | import ( 4 | "crypto/rand" 5 | "fmt" 6 | "github.com/niclabs/tcpaillier" 7 | "math/big" 8 | "testing" 9 | ) 10 | 11 | const k = 7 12 | const l = 10 13 | const s = 1 14 | 15 | const bitSize = 512 16 | 17 | var twelve = big.NewInt(12) 18 | var twentyFive = big.NewInt(25) 19 | var fortyNine = big.NewInt(49) 20 | var threeHundred = big.NewInt(300) 21 | 22 | func TestGenKeyShares(t *testing.T) { 23 | shares, _, err := tcpaillier.NewKey(bitSize, s, l, k) 24 | if err != nil { 25 | t.Errorf("%v", err) 26 | return 27 | } 28 | if len(shares) != l { 29 | t.Errorf("length of shares is %d instead of %d", len(shares), l) 30 | return 31 | } 32 | indexes := make(map[uint8]struct{}) 33 | for i, share := range shares { 34 | if int(share.Index) != i+1 { 35 | t.Errorf("index should have been %d but it is %d", i, share.Index) 36 | return 37 | } 38 | if _, ok := indexes[share.Index]; ok { 39 | t.Errorf("index repeated: %d", share.Index) 40 | return 41 | } 42 | indexes[share.Index] = struct{}{} 43 | } 44 | } 45 | 46 | func TestPubKey_Encrypt(t *testing.T) { 47 | shares, pk, err := tcpaillier.NewKey(bitSize, s, l, k) 48 | if err != nil { 49 | t.Errorf("%v", err) 50 | return 51 | } 52 | encrypted, zk, err := pk.EncryptWithProof(twelve) 53 | if err != nil { 54 | t.Errorf("%v", err) 55 | return 56 | } 57 | if err := zk.Verify(pk, encrypted); err != nil { 58 | t.Errorf("error verifying encryption ZKProof: %v", err) 59 | return 60 | } 61 | decryptShares := make([]*tcpaillier.DecryptionShare, l) 62 | for i, share := range shares { 63 | decryptShare, zk, err := share.PartialDecryptWithProof(encrypted) 64 | if err != nil { 65 | t.Errorf("share %d is not able to decrypt partially the message: %v", share.Index, err) 66 | return 67 | } 68 | if err := zk.Verify(pk, encrypted, decryptShare); err != nil { 69 | t.Errorf("error verifying decryption ZKProof: %v", err) 70 | return 71 | } 72 | decryptShares[i] = decryptShare 73 | } 74 | decrypted, err := pk.CombineShares(decryptShares...) 75 | if err != nil { 76 | t.Errorf("cannot combine shares: %v", err) 77 | return 78 | } 79 | if decrypted.Cmp(twelve) != 0 { 80 | t.Errorf("messages are different. Decrypted is %s and twelve was %s.", decrypted, twelve) 81 | return 82 | } 83 | } 84 | 85 | func TestPubKey_Add(t *testing.T) { 86 | shares, pk, err := tcpaillier.NewKey(bitSize, s, l, k) 87 | if err != nil { 88 | t.Errorf("%v", err) 89 | return 90 | } 91 | encrypted, zk, err := pk.EncryptWithProof(twelve) 92 | if err != nil { 93 | t.Errorf("%v", err) 94 | return 95 | } 96 | if err := zk.Verify(pk, encrypted); err != nil { 97 | t.Errorf("error verifying first encryption ZKProof: %v", err) 98 | return 99 | } 100 | encrypted2, zk, err := pk.EncryptWithProof(twentyFive) 101 | if err != nil { 102 | t.Errorf("%v", err) 103 | return 104 | } 105 | if err := zk.Verify(pk, encrypted2); err != nil { 106 | t.Errorf("error verifying second encryption ZKProof: %v", err) 107 | return 108 | } 109 | 110 | encryptedSum, err := pk.Add(encrypted, encrypted2, encrypted) 111 | if err != nil { 112 | t.Errorf("%v", err) 113 | return 114 | } 115 | 116 | decryptShares := make([]*tcpaillier.DecryptionShare, l) 117 | for i, share := range shares { 118 | decryptShare, zk, err := share.PartialDecryptWithProof(encryptedSum) 119 | if err != nil { 120 | t.Errorf("share %d is not able to decrypt partially the message: %v", share.Index, err) 121 | return 122 | } 123 | if err := zk.Verify(pk, encryptedSum, decryptShare); err != nil { 124 | t.Errorf("error verifying decryption ZKProof: %v", err) 125 | return 126 | } 127 | decryptShares[i] = decryptShare 128 | } 129 | decrypted, err := pk.CombineShares(decryptShares...) 130 | if err != nil { 131 | t.Errorf("cannot combine shares: %v", err) 132 | return 133 | } 134 | if decrypted.Cmp(fortyNine) != 0 { 135 | t.Errorf("messages are different. Decrypted is %d but should have been %s.", decrypted, fortyNine) 136 | return 137 | } 138 | } 139 | 140 | func TestPubKey_AddNegative(t *testing.T) { 141 | shares, pk, err := tcpaillier.NewKey(bitSize, s, l, k) 142 | if err != nil { 143 | t.Errorf("%v", err) 144 | return 145 | } 146 | minusTwelve := new(big.Int).Neg(twelve) 147 | minusTwelve.Mod(minusTwelve, pk.Cache().NToSPlusOne) 148 | encrypted, zk, err := pk.EncryptWithProof(minusTwelve) 149 | if err != nil { 150 | t.Errorf("%v", err) 151 | return 152 | } 153 | if err := zk.Verify(pk, encrypted); err != nil { 154 | t.Errorf("error verifying first encryption ZKProof: %v", err) 155 | return 156 | } 157 | minusTwentyFive := new(big.Int).Neg(twentyFive) 158 | minusTwentyFive.Mod(minusTwentyFive, pk.Cache().NToSPlusOne) 159 | encrypted2, zk, err := pk.EncryptWithProof(minusTwentyFive) 160 | if err != nil { 161 | t.Errorf("%v", err) 162 | return 163 | } 164 | if err := zk.Verify(pk, encrypted2); err != nil { 165 | t.Errorf("error verifying second encryption ZKProof: %v", err) 166 | return 167 | } 168 | 169 | encryptedSum, err := pk.Add(encrypted, encrypted2) 170 | if err != nil { 171 | t.Errorf("%v", err) 172 | return 173 | } 174 | 175 | sum := new(big.Int).Add(minusTwelve, minusTwentyFive) 176 | sum.Mod(sum, pk.N) 177 | decryptShares := make([]*tcpaillier.DecryptionShare, l) 178 | for i, share := range shares { 179 | decryptShare, zk, err := share.PartialDecryptWithProof(encryptedSum) 180 | if err != nil { 181 | t.Errorf("share %d is not able to decrypt partially the message: %v", share.Index, err) 182 | return 183 | } 184 | if err := zk.Verify(pk, encryptedSum, decryptShare); err != nil { 185 | t.Errorf("error verifying decryption ZKProof: %v", err) 186 | return 187 | } 188 | decryptShares[i] = decryptShare 189 | } 190 | decrypted, err := pk.CombineShares(decryptShares...) 191 | if err != nil { 192 | t.Errorf("cannot combine shares: %v", err) 193 | return 194 | } 195 | if decrypted.Cmp(sum) != 0 { 196 | t.Errorf("messages are different:\nDecrypted = %s\n Expected = %s.", decrypted, sum) 197 | return 198 | } 199 | } 200 | 201 | func TestPubKey_Multiply(t *testing.T) { 202 | shares, pk, err := tcpaillier.NewKey(bitSize, s, l, k) 203 | if err != nil { 204 | t.Errorf("%v", err) 205 | return 206 | } 207 | encrypted, zk, err := pk.EncryptWithProof(twelve) 208 | if err != nil { 209 | t.Errorf("error encrypting twelve: %v", err) 210 | return 211 | } 212 | if err := zk.Verify(pk, encrypted); err != nil { 213 | t.Errorf("error verifying first encryption ZKProof: %v", err) 214 | return 215 | } 216 | 217 | encryptedMul, proof, err := pk.MultiplyWithProof(encrypted, twentyFive) 218 | if err != nil { 219 | t.Errorf("Error multiplying twelve for constant %s: %v", twentyFive, err) 220 | return 221 | } 222 | 223 | if err := proof.Verify(pk, encryptedMul, encrypted); err != nil { 224 | t.Errorf("Error verifying mulZKProof: %v", err) 225 | return 226 | } 227 | 228 | decryptShares := make([]*tcpaillier.DecryptionShare, l) 229 | for i, share := range shares { 230 | decryptShare, zk, err := share.PartialDecryptWithProof(encryptedMul) 231 | if err != nil { 232 | t.Errorf("share %d is not able to decrypt partially the message: %v", share.Index, err) 233 | return 234 | } 235 | if err := zk.Verify(pk, encryptedMul, decryptShare); err != nil { 236 | t.Errorf("error verifying decryption ZKProof: %v", err) 237 | return 238 | } 239 | decryptShares[i] = decryptShare 240 | } 241 | decrypted, err := pk.CombineShares(decryptShares...) 242 | if err != nil { 243 | t.Errorf("cannot combine shares: %v", err) 244 | return 245 | } 246 | if decrypted.Cmp(threeHundred) != 0 { 247 | t.Errorf("messages are different. Decrypted is %d but should have been %s.", decrypted, threeHundred) 248 | return 249 | } 250 | } 251 | 252 | func TestPubKey_RandAdd(t *testing.T) { 253 | shares, pk, err := tcpaillier.NewKey(bitSize, s, l, k) 254 | if err != nil { 255 | t.Errorf("%v", err) 256 | return 257 | } 258 | maxRand := new(big.Int).Rsh(pk.N, 1) 259 | rand1, err := rand.Int(rand.Reader, maxRand) 260 | if err != nil { 261 | t.Errorf("%v", err) 262 | return 263 | } 264 | encrypted, zk, err := pk.EncryptWithProof(rand1) 265 | if err != nil { 266 | t.Errorf("%v", err) 267 | return 268 | } 269 | if err := zk.Verify(pk, encrypted); err != nil { 270 | t.Errorf("error verifying first encryption ZKProof: %v", err) 271 | return 272 | } 273 | rand2, err := rand.Int(rand.Reader, maxRand) 274 | if err != nil { 275 | t.Errorf("%v", err) 276 | return 277 | } 278 | encrypted2, zk, err := pk.EncryptWithProof(rand2) 279 | if err != nil { 280 | t.Errorf("%v", err) 281 | return 282 | } 283 | if err := zk.Verify(pk, encrypted2); err != nil { 284 | t.Errorf("error verifying second encryption ZKProof: %v", err) 285 | return 286 | } 287 | randSum := new(big.Int).Add(rand1, rand2) 288 | 289 | encryptedSum, err := pk.Add(encrypted, encrypted2) 290 | if err != nil { 291 | t.Errorf("%v", err) 292 | return 293 | } 294 | 295 | decryptShares := make([]*tcpaillier.DecryptionShare, l) 296 | for i, share := range shares { 297 | decryptShare, zk, err := share.PartialDecryptWithProof(encryptedSum) 298 | if err != nil { 299 | t.Errorf("share %d is not able to decrypt partially the message: %v", share.Index, err) 300 | return 301 | } 302 | if err := zk.Verify(pk, encryptedSum, decryptShare); err != nil { 303 | t.Errorf("error verifying decryption ZKProof: %v", err) 304 | return 305 | } 306 | decryptShares[i] = decryptShare 307 | } 308 | decrypted, err := pk.CombineShares(decryptShares...) 309 | if err != nil { 310 | t.Errorf("cannot combine shares: %v", err) 311 | return 312 | } 313 | if decrypted.Cmp(randSum) != 0 { 314 | t.Errorf("messages are different:\nr1 =%s\nr2 =%s\ndec=%s\nexp=%s\nn =%s\n", rand1, rand2, randSum, decrypted, pk.N) 315 | return 316 | } 317 | } 318 | 319 | func TestPubKey_RandMul(t *testing.T) { 320 | shares, pk, err := tcpaillier.NewKey(bitSize, s, l, k) 321 | if err != nil { 322 | t.Errorf("%v", err) 323 | return 324 | } 325 | maxRand := new(big.Int).Rsh(pk.N, uint(pk.N.BitLen()/2)) 326 | rand1, err := rand.Int(rand.Reader, maxRand) 327 | encrypted, zk, err := pk.EncryptWithProof(rand1) 328 | if err != nil { 329 | t.Errorf("%v", err) 330 | return 331 | } 332 | if err := zk.Verify(pk, encrypted); err != nil { 333 | t.Errorf("error verifying first encryption ZKProof: %v", err) 334 | return 335 | } 336 | rand2, err := rand.Int(rand.Reader, maxRand) 337 | if err != nil { 338 | t.Errorf("%v", err) 339 | return 340 | } 341 | encryptedMul, mzk, err := pk.MultiplyWithProof(encrypted, rand2) 342 | if err != nil { 343 | t.Errorf("%v", err) 344 | return 345 | } 346 | if err := mzk.Verify(pk, encryptedMul, encrypted); err != nil { 347 | t.Errorf("error verifying multiplication ZKProof: %v", err) 348 | return 349 | } 350 | randSum := new(big.Int).Mul(rand1, rand2) 351 | randSum.Mod(randSum, pk.N) 352 | decryptShares := make([]*tcpaillier.DecryptionShare, l) 353 | for i, share := range shares { 354 | decryptShare, zk, err := share.PartialDecryptWithProof(encryptedMul) 355 | if err != nil { 356 | t.Errorf("share %d is not able to decrypt partially the message: %v", share.Index, err) 357 | return 358 | } 359 | if err := zk.Verify(pk, encryptedMul, decryptShare); err != nil { 360 | t.Errorf("error verifying decryption ZKProof: %v", err) 361 | return 362 | } 363 | decryptShares[i] = decryptShare 364 | } 365 | decrypted, err := pk.CombineShares(decryptShares...) 366 | if err != nil { 367 | t.Errorf("cannot combine shares: %v", err) 368 | return 369 | } 370 | if decrypted.Cmp(randSum) != 0 { 371 | t.Errorf("messages are different:\nr1 =%s\nr2 =%s\ndec=%s\nexp=%s\nn =%s\n", rand1, rand2, randSum, decrypted, pk.N) 372 | return 373 | } 374 | } 375 | 376 | func TestPubKey_OverflowAdd(t *testing.T) { 377 | shares, pk, err := tcpaillier.NewKey(bitSize, s, l, k) 378 | if err != nil { 379 | t.Errorf("%v", err) 380 | return 381 | } 382 | maxRand := new(big.Int) 383 | maxRand.SetBit(maxRand, pk.N.BitLen(), 1) 384 | encrypted, zk, err := pk.EncryptWithProof(maxRand) 385 | if err != nil { 386 | t.Errorf("%v", err) 387 | return 388 | } 389 | if err := zk.Verify(pk, encrypted); err != nil { 390 | t.Errorf("error verifying first encryption ZKProof: %v", err) 391 | return 392 | } 393 | sum := new(big.Int).Add(maxRand, maxRand) 394 | sum.Mod(sum, pk.N) 395 | encryptedSum, err := pk.Add(encrypted, encrypted) 396 | if err != nil { 397 | t.Errorf("%v", err) 398 | return 399 | } 400 | decryptShares := make([]*tcpaillier.DecryptionShare, l) 401 | for i, share := range shares { 402 | decryptShare, zk, err := share.PartialDecryptWithProof(encryptedSum) 403 | if err != nil { 404 | t.Errorf("share %d is not able to decrypt partially the message: %v", share.Index, err) 405 | return 406 | } 407 | if err := zk.Verify(pk, encryptedSum, decryptShare); err != nil { 408 | t.Errorf("error verifying decryption ZKProof: %v", err) 409 | return 410 | } 411 | decryptShares[i] = decryptShare 412 | } 413 | decrypted, err := pk.CombineShares(decryptShares...) 414 | if err != nil { 415 | t.Errorf("cannot combine shares: %v", err) 416 | return 417 | } 418 | if decrypted.Cmp(sum) != 0 { 419 | t.Errorf("messages are different:\nmax =%s\ndec=%s\nexp=%s\nn =%s\n", maxRand, sum, decrypted, pk.N) 420 | return 421 | } 422 | } 423 | 424 | func TestPubKey_OverflowMul(t *testing.T) { 425 | shares, pk, err := tcpaillier.NewKey(bitSize, s, l, k) 426 | if err != nil { 427 | t.Errorf("%v", err) 428 | return 429 | } 430 | maxRand := new(big.Int) 431 | maxRand.SetBit(maxRand, pk.N.BitLen(), 1) 432 | encrypted, zk, err := pk.EncryptWithProof(maxRand) 433 | if err != nil { 434 | t.Errorf("%v", err) 435 | return 436 | } 437 | if err := zk.Verify(pk, encrypted); err != nil { 438 | t.Errorf("error verifying first encryption ZKProof: %v", err) 439 | return 440 | } 441 | mul := new(big.Int).Mul(maxRand, maxRand) 442 | mul.Mod(mul, pk.N) 443 | encryptedMul, mzk, err := pk.MultiplyWithProof(encrypted, maxRand) 444 | if err != nil { 445 | t.Errorf("%v", err) 446 | return 447 | } 448 | if err := mzk.Verify(pk, encryptedMul, encrypted); err != nil { 449 | t.Errorf("error verifying multiplication ZKProof: %v", err) 450 | return 451 | } 452 | decryptShares := make([]*tcpaillier.DecryptionShare, l) 453 | for i, share := range shares { 454 | decryptShare, zk, err := share.PartialDecryptWithProof(encryptedMul) 455 | if err != nil { 456 | t.Errorf("share %d is not able to decrypt partially the message: %v", share.Index, err) 457 | return 458 | } 459 | if err := zk.Verify(pk, encryptedMul, decryptShare); err != nil { 460 | t.Errorf("error verifying decryption ZKProof: %v", err) 461 | return 462 | } 463 | decryptShares[i] = decryptShare 464 | } 465 | decrypted, err := pk.CombineShares(decryptShares...) 466 | if err != nil { 467 | t.Errorf("cannot combine shares: %v", err) 468 | return 469 | } 470 | if decrypted.Cmp(mul) != 0 { 471 | t.Errorf("messages are different:\nmax =%s\ndec=%s\nexp=%s\nn =%s\n", maxRand, mul, decrypted, pk.N) 472 | return 473 | } 474 | } 475 | 476 | func TestPubKey_FixedAdd(t *testing.T) { 477 | shares, pk, err := tcpaillier.NewKey(bitSize, s, l, k) 478 | if err != nil { 479 | t.Errorf("%v", err) 480 | return 481 | } 482 | maxRand := new(big.Int).Rsh(pk.N, 1) 483 | rand1, err := rand.Int(rand.Reader, maxRand) 484 | if err != nil { 485 | t.Errorf("%v", err) 486 | return 487 | } 488 | encrypted, zk, err := pk.EncryptFixedWithProof(rand1, big.NewInt(1)) 489 | if err != nil { 490 | t.Errorf("%v", err) 491 | return 492 | } 493 | if err := zk.Verify(pk, encrypted); err != nil { 494 | t.Errorf("error verifying first encryption ZKProof: %v", err) 495 | return 496 | } 497 | rand2, err := rand.Int(rand.Reader, maxRand) 498 | if err != nil { 499 | t.Errorf("%v", err) 500 | return 501 | } 502 | encrypted2, zk, err := pk.EncryptFixedWithProof(rand2, big.NewInt(1)) 503 | if err != nil { 504 | t.Errorf("%v", err) 505 | return 506 | } 507 | if err := zk.Verify(pk, encrypted2); err != nil { 508 | t.Errorf("error verifying second encryption ZKProof: %v", err) 509 | return 510 | } 511 | 512 | encryptedSum, err := pk.Add(encrypted, encrypted2) 513 | if err != nil { 514 | t.Errorf("%v", err) 515 | return 516 | } 517 | 518 | encryptedMul, zkp, err := pk.MultiplyWithProof(encryptedSum, twelve) 519 | if err != nil { 520 | t.Errorf("error verifying addition ZKProof: %v", err) 521 | return 522 | } 523 | if err := zkp.Verify(pk, encryptedMul, encryptedSum); err != nil { 524 | t.Errorf("error verifying multiplication ZKProof: %v", err) 525 | return 526 | } 527 | 528 | randMul := new(big.Int).Add(rand1, rand2) 529 | randMul.Mul(randMul, twelve).Mod(randMul, pk.N) 530 | 531 | decryptShares := make([]*tcpaillier.DecryptionShare, l) 532 | for i, share := range shares { 533 | decryptShare, zk, err := share.PartialDecryptWithProof(encryptedMul) 534 | if err != nil { 535 | t.Errorf("share %d is not able to decrypt partially the message: %v", share.Index, err) 536 | return 537 | } 538 | if err := zk.Verify(pk, encryptedMul, decryptShare); err != nil { 539 | t.Errorf("error verifying decryption ZKProof: %v", err) 540 | return 541 | } 542 | decryptShares[i] = decryptShare 543 | } 544 | decrypted, err := pk.CombineShares(decryptShares...) 545 | if err != nil { 546 | t.Errorf("cannot combine shares: %v", err) 547 | return 548 | } 549 | if decrypted.Cmp(randMul) != 0 { 550 | t.Errorf("messages are different:\nr1 =%s\nr2 =%s\ndec=%s\nexp=%s\nn =%s\n", rand1, rand2, randMul, decrypted, pk.N) 551 | return 552 | } 553 | } 554 | 555 | func ExamplePubKey_Add() { 556 | // First, we create the shares with the parameters provided. 557 | shares, pk, err := tcpaillier.NewKey(512, 1, 5, 3) 558 | if err != nil { 559 | panic(fmt.Sprintf("%v", err)) 560 | } 561 | 562 | // Now we EncryptFixed two values: 12 and 25 563 | encTwelve, zk, err := pk.EncryptWithProof(big.NewInt(12)) 564 | if err != nil { 565 | panic(err) 566 | } 567 | if err := zk.Verify(pk, encTwelve); err != nil { 568 | panic(err) 569 | } 570 | encTwentyFive, zk, err := pk.EncryptWithProof(big.NewInt(25)) 571 | if err != nil { 572 | panic(err) 573 | } 574 | 575 | // We sum them using Add 576 | thirtySevenSum, err := pk.Add(encTwelve, encTwentyFive) 577 | if err != nil { 578 | panic(err) 579 | } 580 | 581 | // We decrypt them with our shares 582 | decryptShares := make([]*tcpaillier.DecryptionShare, l) 583 | for i, share := range shares { 584 | decryptShare, zk, err := share.PartialDecryptWithProof(thirtySevenSum) 585 | if err != nil { 586 | panic(err) 587 | } 588 | if err := zk.Verify(pk, thirtySevenSum, decryptShare); err != nil { 589 | panic(err) 590 | } 591 | decryptShares[i] = decryptShare 592 | } 593 | 594 | // We combine the shares and get the decrypted and summed value 595 | decrypted, err := pk.CombineShares(decryptShares...) 596 | if err != nil { 597 | panic(err) 598 | } 599 | 600 | // It should be 37 601 | fmt.Printf("%s", decrypted) 602 | // Output: 37 603 | } 604 | 605 | func ExamplePubKey_Multiply() { 606 | // First, we create the shares with the parameters provided. 607 | shares, pk, err := tcpaillier.NewKey(512, 1, 5, 3) 608 | if err != nil { 609 | panic(fmt.Sprintf("%v", err)) 610 | } 611 | 612 | // Now we EncryptFixed two values: 12 and 25 613 | encTwelve, zk, err := pk.EncryptWithProof(big.NewInt(12)) 614 | if err != nil { 615 | panic(err) 616 | } 617 | if err := zk.Verify(pk, encTwelve); err != nil { 618 | panic(err) 619 | } 620 | 621 | // We Multiply them 622 | thirtySevenSum, zkp, err := pk.MultiplyWithProof(encTwelve, big.NewInt(25)) 623 | if err != nil { 624 | panic(err) 625 | } 626 | 627 | if err := zkp.Verify(pk, thirtySevenSum, encTwelve); err != nil { 628 | panic(err) 629 | } 630 | 631 | // We decrypt them with our shares 632 | decryptShares := make([]*tcpaillier.DecryptionShare, l) 633 | for i, share := range shares { 634 | decryptShare, zk, err := share.PartialDecryptWithProof(thirtySevenSum) 635 | if err != nil { 636 | panic(err) 637 | } 638 | if err := zk.Verify(pk, thirtySevenSum, decryptShare); err != nil { 639 | panic(err) 640 | } 641 | decryptShares[i] = decryptShare 642 | } 643 | 644 | // We combine the shares and get the decrypted value 645 | decrypted, err := pk.CombineShares(decryptShares...) 646 | if err != nil { 647 | panic(err) 648 | } 649 | 650 | // It should be 300 651 | fmt.Printf("%s", decrypted) 652 | // Output: 300 653 | } 654 | -------------------------------------------------------------------------------- /threshold_share.go: -------------------------------------------------------------------------------- 1 | package tcpaillier 2 | 3 | import ( 4 | "crypto" 5 | "crypto/sha256" 6 | "fmt" 7 | "math/big" 8 | ) 9 | 10 | // KeyShare represents A share of the private key 11 | // used to decrypt values in paillier encryption scheme. 12 | type KeyShare struct { 13 | *PubKey 14 | Index uint8 15 | Si *big.Int 16 | } 17 | 18 | // PartialDecrypt decrypts the encrypted value partially, using only one 19 | // keyShare. 20 | func (ts *KeyShare) PartialDecrypt(c *big.Int) (ds *DecryptionShare, err error) { 21 | cache := ts.Cache() 22 | nToSPlusOne := cache.NToSPlusOne 23 | if c.Cmp(nToSPlusOne) >= 0 || c.Cmp(zero) < 0 { 24 | err = fmt.Errorf("CAlpha must be between 0 (inclusive) and N^(s+1) (exclusive)") 25 | return 26 | } 27 | 28 | DeltaSi2 := new(big.Int) 29 | DeltaSi2.Mul(two, ts.Delta).Mul(DeltaSi2, ts.Si) 30 | 31 | pd := new(big.Int).Exp(c, DeltaSi2, nToSPlusOne) 32 | 33 | ds = &DecryptionShare{ 34 | Index: ts.Index, 35 | Ci: pd, 36 | } 37 | 38 | return 39 | } 40 | 41 | // PartialDecryptWithProof returns A DecryptionShare, that is composed by A ZKProof and 42 | // A partially decrypted value. 43 | func (ts *KeyShare) PartialDecryptWithProof(c *big.Int) (ds *DecryptionShare, zk *DecryptShareZK, err error) { 44 | ds, err = ts.PartialDecrypt(c) 45 | if err != nil { 46 | return 47 | } 48 | zk, err = ts.PartialDecryptProof(c, ds) 49 | 50 | return 51 | } 52 | 53 | func (ts *KeyShare) PartialDecryptProof(c *big.Int, ds *DecryptionShare) (zk *DecryptShareZK, err error) { 54 | 55 | cache := ts.Cache() 56 | nToSPlusOne := cache.NToSPlusOne 57 | 58 | numBits := int(ts.S+2)*int(ts.K) + crypto.SHA256.Size()*8 59 | r, err := RandomInt(numBits) 60 | if err != nil { 61 | return 62 | } 63 | cTo4 := new(big.Int).Exp(c, big.NewInt(4), nToSPlusOne) 64 | v := ts.V 65 | vi := ts.Vi[ts.Index-1] 66 | 67 | a := new(big.Int).Exp(cTo4, r, nToSPlusOne) 68 | b := new(big.Int).Exp(v, r, nToSPlusOne) 69 | 70 | ciTo2 := new(big.Int).Exp(ds.Ci, two, nToSPlusOne) 71 | 72 | hash := sha256.New() 73 | hash.Write(a.Bytes()) 74 | hash.Write(b.Bytes()) 75 | hash.Write(cTo4.Bytes()) 76 | hash.Write(ciTo2.Bytes()) 77 | eBytes := hash.Sum(nil) 78 | 79 | e := new(big.Int).SetBytes(eBytes) 80 | 81 | eSiDelta := new(big.Int) 82 | eSiDelta.Mul(ts.Si, e).Mul(eSiDelta, ts.Delta) 83 | z := new(big.Int).Add(eSiDelta, r) 84 | 85 | zk = &DecryptShareZK{ 86 | Vi: vi, 87 | E: e, 88 | V: v, 89 | Z: z, 90 | } 91 | return 92 | } 93 | -------------------------------------------------------------------------------- /zk_proof.go: -------------------------------------------------------------------------------- 1 | package tcpaillier 2 | 3 | import ( 4 | "crypto/sha256" 5 | "fmt" 6 | "math/big" 7 | ) 8 | 9 | // EncryptZK represents A ZKProof related to the encryption 10 | // of A value. 11 | type EncryptZK struct { 12 | B, W, Z *big.Int 13 | } 14 | 15 | // MulZK represents A ZKProof related to the multiplication 16 | // of an encrypted value by A constant. 17 | type MulZK struct { 18 | CAlpha, A, B, W, Y, Z *big.Int 19 | } 20 | 21 | // DecryptShareZK represents A ZKProof related to the decryption 22 | // of an encrypted share by A constant. 23 | type DecryptShareZK struct { 24 | V, Vi, Z, E *big.Int 25 | } 26 | 27 | // Verify verifies the Encryption ZKProof. 28 | func (zk *EncryptZK) Verify(pk *PubKey, vals ...interface{}) error { 29 | 30 | if len(vals) != 1 { 31 | return fmt.Errorf("the extra value for verification should be only the encrypted value") 32 | } 33 | 34 | c, ok := vals[0].(*big.Int) 35 | if !ok { 36 | return fmt.Errorf("cannot cast first verification value as A *big.Int") 37 | } 38 | 39 | cache := pk.Cache() 40 | nPlusOne := cache.NPlusOne 41 | nToSPlusOne := cache.NToSPlusOne 42 | nToS := cache.NToS 43 | 44 | hash := sha256.New() 45 | hash.Write(c.Bytes()) 46 | hash.Write(zk.B.Bytes()) 47 | eHash := hash.Sum(nil) 48 | e := new(big.Int).SetBytes(eHash) 49 | 50 | // (n+1)^W % n^(s+1) 51 | nPlusOneToW := new(big.Int).Exp(nPlusOne, zk.W, nToSPlusOne) 52 | // Z^n % n^(s+1) 53 | zToN := new(big.Int).Exp(zk.Z, nToS, nToSPlusOne) 54 | // (n+1)^W*Z^n % n^(s+1) 55 | left := new(big.Int) 56 | left.Mul(nPlusOneToW, zToN).Mod(left, nToSPlusOne) 57 | 58 | // CAlpha^E % n^(s+1) 59 | cToE := new(big.Int).Exp(c, e, nToSPlusOne) 60 | // B*CAlpha^E % n^(s+1) 61 | right := new(big.Int) 62 | right.Mul(zk.B, cToE).Mod(right, nToSPlusOne) 63 | 64 | if left.Cmp(right) != 0 { 65 | return fmt.Errorf("zkproof failed") 66 | } 67 | return nil 68 | } 69 | 70 | // Verify verifies the Multiplication ZKProof. 71 | func (zk *MulZK) Verify(pk *PubKey, vals ...interface{}) error { 72 | 73 | if len(vals) != 2 { 74 | return fmt.Errorf("the extra values for verification should be the result and the encrypted value") 75 | } 76 | 77 | d, ok := vals[0].(*big.Int) 78 | if !ok { 79 | return fmt.Errorf("cannot cast first verification value as A *big.Int") 80 | } 81 | 82 | ca, ok := vals[1].(*big.Int) 83 | if !ok { 84 | return fmt.Errorf("cannot cast first verification value as A *big.Int") 85 | } 86 | 87 | 88 | cache := pk.Cache() 89 | nPlusOne := cache.NPlusOne 90 | nToSPlusOne := cache.NToSPlusOne 91 | nToS := cache.NToS 92 | 93 | hash := sha256.New() 94 | hash.Write(ca.Bytes()) 95 | hash.Write(zk.CAlpha.Bytes()) 96 | hash.Write(d.Bytes()) 97 | hash.Write(zk.A.Bytes()) 98 | hash.Write(zk.B.Bytes()) 99 | eBytes := hash.Sum(nil) 100 | 101 | e := new(big.Int).SetBytes(eBytes) 102 | 103 | // (n+1)^W % n^(s+1) 104 | nPlusOneToW := new(big.Int).Exp(nPlusOne, zk.W, nToSPlusOne) 105 | // Z^n % n^(s+1) 106 | zToNToS := new(big.Int).Exp(zk.Z, nToS, nToSPlusOne) 107 | // ((n+1)^W % n^(s+1)) * (Z^n % n^(s+1)) % n^(s+1) 108 | zk1 := new(big.Int) 109 | zk1.Mul(nPlusOneToW, zToNToS).Mod(zk1, nToSPlusOne) 110 | 111 | // CAlpha^E % n^(s+1) 112 | cToE := new(big.Int).Exp(zk.CAlpha, e, nToSPlusOne) 113 | // B * CAlpha^E % n^(s+1) 114 | zk2 := new(big.Int) 115 | zk2.Mul(cToE, zk.B).Mod(zk2, nToSPlusOne) 116 | 117 | if zk1.Cmp(zk2) != 0 { 118 | return fmt.Errorf("zkproof failed") 119 | } 120 | 121 | // ca^W % n^(s+1) 122 | caToW := new(big.Int).Exp(ca, zk.W, nToSPlusOne) 123 | // (Y^n % n^(s+1) 124 | yToNToS := new(big.Int).Exp(zk.Y, nToS, nToSPlusOne) 125 | // (ca^W % n^(s+1)) * (Y^n % n^(s+1)) % n^(s+1) 126 | zk3 := new(big.Int) 127 | zk3.Mul(caToW, yToNToS).Mod(zk3, nToSPlusOne) 128 | 129 | // d^E % n^(s+1) 130 | dToE := new(big.Int).Exp(d, e, nToSPlusOne) 131 | // A*d^E % n^(s+1) 132 | zk4 := new(big.Int).Mul(dToE, zk.A) 133 | zk4.Mod(zk4, nToSPlusOne) 134 | 135 | if zk3.Cmp(zk4) != 0 { 136 | return fmt.Errorf("zkproof failed") 137 | } 138 | return nil 139 | } 140 | 141 | // Verify verifies the ZKProof inside A DecryptionShare 142 | func (zk *DecryptShareZK) Verify(pk *PubKey, vals ...interface{}) error { 143 | 144 | 145 | if len(vals) != 2 { 146 | return fmt.Errorf("the extra values for verification should be only the encrypted value and the decrypted share") 147 | } 148 | 149 | c, ok := vals[0].(*big.Int) 150 | if !ok { 151 | return fmt.Errorf("cannot cast first verification value as A *big.Int") 152 | } 153 | 154 | ds, ok := vals[1].(*DecryptionShare) 155 | if !ok { 156 | return fmt.Errorf("cannot cast second verification value as A decryptionShare") 157 | } 158 | 159 | cache := pk.Cache() 160 | nToSPlusOne := cache.NToSPlusOne 161 | cTo4 := new(big.Int).Exp(c, big.NewInt(4), nToSPlusOne) 162 | cTo4z := new(big.Int).Exp(cTo4, zk.Z, nToSPlusOne) 163 | ciTo2 := new(big.Int).Exp(ds.Ci, two, nToSPlusOne) 164 | minusE := new(big.Int).Neg(zk.E) 165 | minusTwoE := new(big.Int).Mul(minusE, two) 166 | ciToMinus2e := new(big.Int).Exp(ds.Ci, minusTwoE, nToSPlusOne) 167 | a := new(big.Int).Mul(cTo4z, ciToMinus2e) 168 | a.Mod(a, nToSPlusOne) 169 | 170 | vToZ := new(big.Int).Exp(zk.V, zk.Z, nToSPlusOne) 171 | viToMinusE := new(big.Int).Exp(zk.Vi, minusE, nToSPlusOne) 172 | b := new(big.Int).Mul(vToZ, viToMinusE) 173 | b.Mod(b, nToSPlusOne) 174 | 175 | hash := sha256.New() 176 | hash.Write(a.Bytes()) 177 | hash.Write(b.Bytes()) 178 | hash.Write(cTo4.Bytes()) 179 | hash.Write(ciTo2.Bytes()) 180 | eBytes := hash.Sum(nil) 181 | 182 | e := new(big.Int).SetBytes(eBytes) 183 | 184 | if e.Cmp(zk.E) != 0 { 185 | return fmt.Errorf("zkproof failed") 186 | } 187 | return nil 188 | } 189 | --------------------------------------------------------------------------------