├── .github └── workflows │ └── tests.yml ├── .gitignore ├── .prettierrc ├── LICENSE ├── README.md ├── esm └── package.json ├── package-lock.json ├── package.json ├── src ├── csprng.node.ts ├── csprng.ts └── index.ts ├── test └── index.test.js ├── tsconfig.esm.json └── tsconfig.json /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Github CI 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-22.04 8 | steps: 9 | - uses: actions/checkout@v3 10 | - name: setup node 11 | uses: actions/setup-node@v3 12 | with: 13 | node-version: 16.x # Support 16 and later 14 | - run: npm ci 15 | - run: npm run lint 16 | - run: npm run test 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules/ 3 | *.gitignored.* 4 | /*.d.ts 5 | /*.js 6 | /*.js.map 7 | /esm/*.d.ts 8 | /esm/*.js 9 | /esm/*.js.map -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 100, 3 | "trailingComma": "all", 4 | "arrowParens": "always", 5 | "bracketSpacing": false, 6 | "singleQuote": true 7 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2023 Horkos, Inc. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # shamir-secret-sharing 2 | 3 | ![Github CI](https://github.com/privy-io/shamir-secret-sharing/workflows/Github%20CI/badge.svg) 4 | 5 | Simple, independently audited, zero-dependency TypeScript implementation of [Shamir's Secret Sharing algorithm](https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing). 6 | 7 | Uses GF(2^8). Works on `Uint8Array` objects. Implementation inspired by [hashicorp/vault](https://github.com/hashicorp/vault/tree/main/shamir). 8 | 9 | Both Node and browser environments are supported. 10 | 11 | Made with ❤️ by [Privy](https://privy.io). 12 | 13 | ## Security considerations 14 | 15 | This library has been independently audited by [Cure53](https://cure53.de) ([audit report](https://cure53.de/audit-report_privy-sss-library.pdf)) and [Zellic](https://www.zellic.io/) ([audit report](https://github.com/Zellic/publications/blob/master/Privy_Shamir_Secret_Sharing_-_Zellic_Audit_Report.pdf)). 16 | 17 | There are a couple of considerations for proper use of this library. 18 | 19 | 1. Resistance to side channel attacks: JavaScript is a garbage-collected, just-in-time compiled language and it is thus unrealistic to achieve true constant-time guarantees. Where possible, we aim to achieve algorithmic constant-time. 20 | 2. This library is not responsible for verifying the result of share reconstruction. Incorrect or corrupted shares will produce an incorrect value. Thus, it is the responsibility of users of this library to verify the integrity of the reconstructed secret. 21 | 3. Secrets should ideally be uniformly distributed at random. If this is not the case, it is recommended to first encrypt the value and split the encryption key. 22 | 23 | ## Usage 24 | 25 | We can `split` a secret into shares and later `combine` the shares to reconstruct the secret. 26 | 27 | ```typescript 28 | import {split, combine} from 'shamir-secret-sharing'; 29 | 30 | const toUint8Array = (data: string) => new TextEncoder().encode(data); 31 | 32 | // Example of splitting user input 33 | const input = document.querySelector("input#secret").value.normalize('NFKC'); 34 | const secret = toUint8Array(input); 35 | const [share1, share2, share3] = await split(secret, 3, 2); 36 | const reconstructed = await combine([share1, share3]); 37 | console.log(btoa(reconstructed) === btoa(secret)); // true 38 | 39 | // Example of splitting random entropy 40 | const randomEntropy = crypto.getRandomValues(new Uint8Array(16)); 41 | const [share1, share2, share3] = await split(randomEntropy, 3, 2); 42 | const reconstructed = await combine([share2, share3]); 43 | console.log(btoa(reconstructed) === btoa(randomEntropy)); // true 44 | 45 | // Example of splitting symmetric key 46 | const key = await crypto.subtle.generateKey( 47 | { 48 | name: "AES-GCM", 49 | length: 256 50 | }, 51 | true, 52 | ["encrypt", "decrypt"] 53 | ); 54 | const exportedKeyBuffer = await crypto.subtle.exportKey('raw', key); 55 | const exportedKey = new Uint8Array(exportedKeyBuffer); 56 | const [share1, share2, share3] = await split(exportedKey, 3, 2); 57 | const reconstructed = await combine([share2, share1]); 58 | console.log(btoa(reconstructed) === btoa(exportedKey)); // true 59 | ``` 60 | 61 | ## API 62 | 63 | This package exposes two functions: `split` and `combine`. 64 | 65 | #### split 66 | 67 | ```ts 68 | /** 69 | * Splits a `secret` into `shares` number of shares, requiring `threshold` of them to reconstruct `secret`. 70 | * 71 | * @param secret The secret value to split into shares. 72 | * @param shares The total number of shares to split `secret` into. Must be at least 2 and at most 255. 73 | * @param threshold The minimum number of shares required to reconstruct `secret`. Must be at least 2 and at most 255. 74 | * @returns A list of `shares` shares. 75 | */ 76 | declare function split(secret: Uint8Array, shares: number, threshold: number): Promise; 77 | ``` 78 | 79 | #### combine 80 | 81 | ```ts 82 | /** 83 | * Combines `shares` to reconstruct the secret. 84 | * 85 | * @param shares A list of shares to reconstruct the secret from. Must be at least 2 and at most 255. 86 | * @returns The reconstructed secret. 87 | */ 88 | declare function combine(shares: Uint8Array[]): Promise; 89 | ``` 90 | ## Contributions 91 | 92 | The shamir-secret-sharing library is not currently open to external contributions. 93 | 94 | Please [submit an Issue](https://github.com/privy-io/shamir-secret-sharing/issues/new) and fill 95 | out the issue with as much information as possible if you have found a bug in need of 96 | fixing. 97 | 98 | You can also [submit an Issue](https://github.com/privy-io/shamir-secret-sharing/issues/new) to 99 | request new features, or to suggest changes to existing features. 100 | 101 | ## License 102 | 103 | Apache-2.0. See the [license file](LICENSE). 104 | -------------------------------------------------------------------------------- /esm/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "module", 3 | "browser": { 4 | "node:crypto": false 5 | }, 6 | "node": { 7 | "./csprng": "./esm/csprng.node.js" 8 | } 9 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "shamir-secret-sharing", 3 | "version": "0.0.4", 4 | "description": "Simple, independently audited, zero-dependency TypeScript implementation of Shamir's Secret Sharing algorithm", 5 | "keywords": [ 6 | "shamir", 7 | "secret", 8 | "sharing", 9 | "threshold", 10 | "cryptography", 11 | "crypto", 12 | "keys", 13 | "mnemonic", 14 | "typescript", 15 | "node", 16 | "browser", 17 | "web3" 18 | ], 19 | "browser": { 20 | "node:crypto": false 21 | }, 22 | "exports": { 23 | ".": { 24 | "types": "./index.d.ts", 25 | "import": "./esm/index.js", 26 | "default": "./index.js" 27 | }, 28 | "./csprng": { 29 | "types": "./csprng.d.ts", 30 | "node": { 31 | "import": "./esm/csprng.node.js", 32 | "require": "./csprng.node.js" 33 | }, 34 | "import": "./esm/csprng.js", 35 | "require": "./csprng.js" 36 | } 37 | }, 38 | "files": [ 39 | "/*.js", 40 | "/*.js.map", 41 | "/*.d.ts", 42 | "esm", 43 | "src" 44 | ], 45 | "scripts": { 46 | "clean": "rm *.{js,d.ts,js.map} esm/*.{js,d.ts,js.map} 2> /dev/null; echo clean", 47 | "prebuild": "npm run clean", 48 | "build": "tsc && tsc -p tsconfig.esm.json", 49 | "lint": "prettier --check 'src/**/*.ts' 'test/**/*.js'", 50 | "pretest": "npm run build", 51 | "test": "jest --testMatch \"**/test/**/*.test.js\"", 52 | "prepublishOnly": "npm run build" 53 | }, 54 | "author": "privy.io", 55 | "repository": { 56 | "type": "git", 57 | "url": "https://github.com/privy-io/shamir-secret-sharing" 58 | }, 59 | "license": "Apache-2.0", 60 | "devDependencies": { 61 | "jest": "^29.5.0", 62 | "prettier": "^2.8.3", 63 | "typescript": "^4.9.4" 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/csprng.node.ts: -------------------------------------------------------------------------------- 1 | import {randomBytes} from 'node:crypto'; 2 | 3 | export function getRandomBytes(numBytes: number): Uint8Array { 4 | return new Uint8Array(randomBytes(numBytes).buffer); 5 | } 6 | -------------------------------------------------------------------------------- /src/csprng.ts: -------------------------------------------------------------------------------- 1 | export function getRandomBytes(numBytes: number): Uint8Array { 2 | return crypto.getRandomValues(new Uint8Array(numBytes)); 3 | } 4 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import {getRandomBytes} from 'shamir-secret-sharing/csprng'; 2 | 3 | // The Polynomial used is: x⁸ + x⁴ + x³ + x + 1 4 | // 5 | // Lookup tables pulled from: 6 | // 7 | // * https://github.com/hashicorp/vault/blob/9d46671659cbfe7bbd3e78d1073dfb22936a4437/shamir/tables.go 8 | // * http://www.samiam.org/galois.html 9 | // 10 | // 0xe5 (229) is used as the generator. 11 | 12 | // Provides log(X)/log(g) at each index X. 13 | const LOG_TABLE: Readonly = new Uint8Array([ 14 | 0x00, 0xff, 0xc8, 0x08, 0x91, 0x10, 0xd0, 0x36, 0x5a, 0x3e, 0xd8, 0x43, 0x99, 0x77, 0xfe, 0x18, 15 | 0x23, 0x20, 0x07, 0x70, 0xa1, 0x6c, 0x0c, 0x7f, 0x62, 0x8b, 0x40, 0x46, 0xc7, 0x4b, 0xe0, 0x0e, 16 | 0xeb, 0x16, 0xe8, 0xad, 0xcf, 0xcd, 0x39, 0x53, 0x6a, 0x27, 0x35, 0x93, 0xd4, 0x4e, 0x48, 0xc3, 17 | 0x2b, 0x79, 0x54, 0x28, 0x09, 0x78, 0x0f, 0x21, 0x90, 0x87, 0x14, 0x2a, 0xa9, 0x9c, 0xd6, 0x74, 18 | 0xb4, 0x7c, 0xde, 0xed, 0xb1, 0x86, 0x76, 0xa4, 0x98, 0xe2, 0x96, 0x8f, 0x02, 0x32, 0x1c, 0xc1, 19 | 0x33, 0xee, 0xef, 0x81, 0xfd, 0x30, 0x5c, 0x13, 0x9d, 0x29, 0x17, 0xc4, 0x11, 0x44, 0x8c, 0x80, 20 | 0xf3, 0x73, 0x42, 0x1e, 0x1d, 0xb5, 0xf0, 0x12, 0xd1, 0x5b, 0x41, 0xa2, 0xd7, 0x2c, 0xe9, 0xd5, 21 | 0x59, 0xcb, 0x50, 0xa8, 0xdc, 0xfc, 0xf2, 0x56, 0x72, 0xa6, 0x65, 0x2f, 0x9f, 0x9b, 0x3d, 0xba, 22 | 0x7d, 0xc2, 0x45, 0x82, 0xa7, 0x57, 0xb6, 0xa3, 0x7a, 0x75, 0x4f, 0xae, 0x3f, 0x37, 0x6d, 0x47, 23 | 0x61, 0xbe, 0xab, 0xd3, 0x5f, 0xb0, 0x58, 0xaf, 0xca, 0x5e, 0xfa, 0x85, 0xe4, 0x4d, 0x8a, 0x05, 24 | 0xfb, 0x60, 0xb7, 0x7b, 0xb8, 0x26, 0x4a, 0x67, 0xc6, 0x1a, 0xf8, 0x69, 0x25, 0xb3, 0xdb, 0xbd, 25 | 0x66, 0xdd, 0xf1, 0xd2, 0xdf, 0x03, 0x8d, 0x34, 0xd9, 0x92, 0x0d, 0x63, 0x55, 0xaa, 0x49, 0xec, 26 | 0xbc, 0x95, 0x3c, 0x84, 0x0b, 0xf5, 0xe6, 0xe7, 0xe5, 0xac, 0x7e, 0x6e, 0xb9, 0xf9, 0xda, 0x8e, 27 | 0x9a, 0xc9, 0x24, 0xe1, 0x0a, 0x15, 0x6b, 0x3a, 0xa0, 0x51, 0xf4, 0xea, 0xb2, 0x97, 0x9e, 0x5d, 28 | 0x22, 0x88, 0x94, 0xce, 0x19, 0x01, 0x71, 0x4c, 0xa5, 0xe3, 0xc5, 0x31, 0xbb, 0xcc, 0x1f, 0x2d, 29 | 0x3b, 0x52, 0x6f, 0xf6, 0x2e, 0x89, 0xf7, 0xc0, 0x68, 0x1b, 0x64, 0x04, 0x06, 0xbf, 0x83, 0x38, 30 | ]); 31 | 32 | // Provides the exponentiation value at each index X. 33 | const EXP_TABLE: Readonly = new Uint8Array([ 34 | 0x01, 0xe5, 0x4c, 0xb5, 0xfb, 0x9f, 0xfc, 0x12, 0x03, 0x34, 0xd4, 0xc4, 0x16, 0xba, 0x1f, 0x36, 35 | 0x05, 0x5c, 0x67, 0x57, 0x3a, 0xd5, 0x21, 0x5a, 0x0f, 0xe4, 0xa9, 0xf9, 0x4e, 0x64, 0x63, 0xee, 36 | 0x11, 0x37, 0xe0, 0x10, 0xd2, 0xac, 0xa5, 0x29, 0x33, 0x59, 0x3b, 0x30, 0x6d, 0xef, 0xf4, 0x7b, 37 | 0x55, 0xeb, 0x4d, 0x50, 0xb7, 0x2a, 0x07, 0x8d, 0xff, 0x26, 0xd7, 0xf0, 0xc2, 0x7e, 0x09, 0x8c, 38 | 0x1a, 0x6a, 0x62, 0x0b, 0x5d, 0x82, 0x1b, 0x8f, 0x2e, 0xbe, 0xa6, 0x1d, 0xe7, 0x9d, 0x2d, 0x8a, 39 | 0x72, 0xd9, 0xf1, 0x27, 0x32, 0xbc, 0x77, 0x85, 0x96, 0x70, 0x08, 0x69, 0x56, 0xdf, 0x99, 0x94, 40 | 0xa1, 0x90, 0x18, 0xbb, 0xfa, 0x7a, 0xb0, 0xa7, 0xf8, 0xab, 0x28, 0xd6, 0x15, 0x8e, 0xcb, 0xf2, 41 | 0x13, 0xe6, 0x78, 0x61, 0x3f, 0x89, 0x46, 0x0d, 0x35, 0x31, 0x88, 0xa3, 0x41, 0x80, 0xca, 0x17, 42 | 0x5f, 0x53, 0x83, 0xfe, 0xc3, 0x9b, 0x45, 0x39, 0xe1, 0xf5, 0x9e, 0x19, 0x5e, 0xb6, 0xcf, 0x4b, 43 | 0x38, 0x04, 0xb9, 0x2b, 0xe2, 0xc1, 0x4a, 0xdd, 0x48, 0x0c, 0xd0, 0x7d, 0x3d, 0x58, 0xde, 0x7c, 44 | 0xd8, 0x14, 0x6b, 0x87, 0x47, 0xe8, 0x79, 0x84, 0x73, 0x3c, 0xbd, 0x92, 0xc9, 0x23, 0x8b, 0x97, 45 | 0x95, 0x44, 0xdc, 0xad, 0x40, 0x65, 0x86, 0xa2, 0xa4, 0xcc, 0x7f, 0xec, 0xc0, 0xaf, 0x91, 0xfd, 46 | 0xf7, 0x4f, 0x81, 0x2f, 0x5b, 0xea, 0xa8, 0x1c, 0x02, 0xd1, 0x98, 0x71, 0xed, 0x25, 0xe3, 0x24, 47 | 0x06, 0x68, 0xb3, 0x93, 0x2c, 0x6f, 0x3e, 0x6c, 0x0a, 0xb8, 0xce, 0xae, 0x74, 0xb1, 0x42, 0xb4, 48 | 0x1e, 0xd3, 0x49, 0xe9, 0x9c, 0xc8, 0xc6, 0xc7, 0x22, 0x6e, 0xdb, 0x20, 0xbf, 0x43, 0x51, 0x52, 49 | 0x66, 0xb2, 0x76, 0x60, 0xda, 0xc5, 0xf3, 0xf6, 0xaa, 0xcd, 0x9a, 0xa0, 0x75, 0x54, 0x0e, 0x01, 50 | ]); 51 | 52 | // Combines two numbers in GF(2^8). 53 | // This can be used for both addition and subtraction. 54 | function add(a: number, b: number): number { 55 | if (!Number.isInteger(a) || a < 0 || a > 255) { 56 | throw new RangeError('Number is out of Uint8 range'); 57 | } 58 | if (!Number.isInteger(b) || b < 0 || b > 255) { 59 | throw new RangeError('Number is out of Uint8 range'); 60 | } 61 | return a ^ b; 62 | } 63 | 64 | // Divides two numbers in GF(2^8). 65 | function div(a: number, b: number): number { 66 | if (!Number.isInteger(a) || a < 0 || a > 255) { 67 | throw new RangeError('Number is out of Uint8 range'); 68 | } 69 | if (!Number.isInteger(b) || b < 0 || b > 255) { 70 | throw new RangeError('Number is out of Uint8 range'); 71 | } 72 | // This should never happen 73 | if (b === 0) { 74 | throw new Error('cannot divide by zero'); 75 | } 76 | 77 | const logA = LOG_TABLE[a]!; 78 | const logB = LOG_TABLE[b]!; 79 | const diff = (logA - logB + 255) % 255; 80 | const result = EXP_TABLE[diff]!; 81 | 82 | return a === 0 ? 0 : result; 83 | } 84 | 85 | // Multiplies two numbers in GF(2^8). 86 | function mult(a: number, b: number): number { 87 | if (!Number.isInteger(a) || a < 0 || a > 255) { 88 | throw new RangeError('Number is out of Uint8 range'); 89 | } 90 | if (!Number.isInteger(b) || b < 0 || b > 255) { 91 | throw new RangeError('Number is out of Uint8 range'); 92 | } 93 | const logA = LOG_TABLE[a]!; 94 | const logB = LOG_TABLE[b]!; 95 | const sum = (logA + logB) % 255; 96 | const result = EXP_TABLE[sum]!; 97 | 98 | return a === 0 || b === 0 ? 0 : result; 99 | } 100 | 101 | // Takes N sample points and returns the value at a given x using a lagrange interpolation. 102 | function interpolatePolynomial(xSamples: Uint8Array, ySamples: Uint8Array, x: number): number { 103 | if (xSamples.length !== ySamples.length) { 104 | throw new Error('sample length mistmatch'); 105 | } 106 | 107 | const limit = xSamples.length; 108 | 109 | let basis = 0; 110 | let result = 0; 111 | 112 | for (let i = 0; i < limit; i++) { 113 | basis = 1; 114 | 115 | for (let j = 0; j < limit; ++j) { 116 | if (i === j) { 117 | continue; 118 | } 119 | const num = add(x, xSamples[j]!); 120 | const denom = add(xSamples[i]!, xSamples[j]!); 121 | const term = div(num, denom); 122 | basis = mult(basis, term); 123 | } 124 | 125 | result = add(result, mult(ySamples[i]!, basis)); 126 | } 127 | 128 | return result; 129 | } 130 | 131 | // Evaluates a polynomial with the given x using Horner's method. 132 | function evaluate(coefficients: Uint8Array, x: number, degree: number) { 133 | if (x === 0) { 134 | throw new Error('cannot evaluate secret polynomial at zero'); 135 | } 136 | 137 | let result = coefficients[degree]!; 138 | 139 | for (let i = degree - 1; i >= 0; i--) { 140 | const coefficient = coefficients[i]!; 141 | result = add(mult(result, x), coefficient); 142 | } 143 | 144 | return result; 145 | } 146 | 147 | // Creates a pseudo-random set of coefficients for a polynomial. 148 | function newCoefficients(intercept: number, degree: number): Readonly { 149 | const coefficients = new Uint8Array(degree + 1); 150 | coefficients[0] = intercept; 151 | coefficients.set(getRandomBytes(degree), 1); 152 | return coefficients; 153 | } 154 | 155 | // Creates a set of values from [1, 256). 156 | // Returns a psuedo-random shuffling of the set. 157 | function newCoordinates(): Readonly { 158 | const coordinates = new Uint8Array(255); 159 | for (let i = 0; i < 255; i++) { 160 | coordinates[i] = i + 1; 161 | } 162 | 163 | // Pseudo-randomize the array of coordinates. 164 | // 165 | // This impl maps almost perfectly because both of the lists (coordinates and randomIndices) 166 | // have a length of 255 and byte values are between 0 and 255 inclusive. The only value that 167 | // does not map neatly here is if the random byte is 255, since that value used as an index 168 | // would be out of bounds. Thus, for bytes whose value is 255, wrap around to 0. 169 | // 170 | // WARNING: This shuffle is biased and should NOT be used if an unbiased shuffle is required. 171 | // 172 | // However, Shamir-based secret sharing does not require any particular indexing (shuffled or 173 | // not) for its security properties to hold; this means including the biased shuffle is not 174 | // itself problematic here. 175 | const randomIndices = getRandomBytes(255); 176 | for (let i = 0; i < 255; i++) { 177 | const j = randomIndices[i]! % 255; // Make sure to handle the case where the byte is 255. 178 | const temp = coordinates[i]!; 179 | coordinates[i] = coordinates[j]!; 180 | coordinates[j] = temp; 181 | } 182 | 183 | return coordinates; 184 | } 185 | 186 | // Helpers for declarative argument validation. 187 | const AssertArgument = { 188 | instanceOf(object: any, constructor: Function, message: string) { 189 | if (object.constructor !== constructor) { 190 | throw new TypeError(message); 191 | } 192 | }, 193 | 194 | inRange(n: number, start: number, until: number, message: string) { 195 | if (!(start < until && n >= start && n < until)) { 196 | throw new RangeError(message); 197 | } 198 | }, 199 | 200 | greaterThanOrEqualTo(a: number, b: number, message: string) { 201 | if (a < b) { 202 | throw new Error(message); 203 | } 204 | }, 205 | 206 | equalTo(a: any, b: any, message: string) { 207 | if (a !== b) { 208 | throw new Error(message); 209 | } 210 | }, 211 | }; 212 | 213 | /** 214 | * Splits a `secret` into `shares` number of shares, requiring `threshold` of them to reconstruct `secret`. 215 | * 216 | * @param secret The secret value to split into shares. 217 | * @param shares The total number of shares to split `secret` into. Must be at least 2 and at most 255. 218 | * @param threshold The minimum number of shares required to reconstruct `secret`. Must be at least 2 and at most 255. 219 | * @returns A list of `shares` shares. 220 | */ 221 | export async function split( 222 | secret: Uint8Array, 223 | shares: number, 224 | threshold: number, 225 | ): Promise { 226 | // secret must be a non-empty Uint8Array 227 | AssertArgument.instanceOf(secret, Uint8Array, 'secret must be a Uint8Array'); 228 | AssertArgument.greaterThanOrEqualTo(secret.byteLength, 1, 'secret cannot be empty'); 229 | 230 | // shares must be a number in the range [2, 256) 231 | AssertArgument.instanceOf(shares, Number, 'shares must be a number'); 232 | AssertArgument.inRange(shares, 2, 256, 'shares must be at least 2 and at most 255'); 233 | 234 | // threshold must be a number in the range [2, 256) 235 | AssertArgument.instanceOf(threshold, Number, 'threshold must be a number'); 236 | AssertArgument.inRange(threshold, 2, 256, 'threshold must be at least 2 and at most 255'); 237 | 238 | // total number of shares must be greater than or equal to the required threshold 239 | AssertArgument.greaterThanOrEqualTo(shares, threshold, 'shares cannot be less than threshold'); 240 | 241 | const result: Uint8Array[] = []; 242 | const secretLength = secret.byteLength; 243 | const xCoordinates = newCoordinates(); 244 | 245 | for (let i = 0; i < shares; i++) { 246 | const share = new Uint8Array(secretLength + 1); 247 | share[secretLength] = xCoordinates[i]!; 248 | result.push(share); 249 | } 250 | 251 | const degree = threshold - 1; 252 | 253 | for (let i = 0; i < secretLength; i++) { 254 | const byte = secret[i]!; 255 | const coefficients = newCoefficients(byte, degree); 256 | 257 | for (let j = 0; j < shares; ++j) { 258 | const x = xCoordinates[j]!; 259 | const y = evaluate(coefficients, x, degree); 260 | result[j]![i] = y; 261 | } 262 | } 263 | 264 | return result; 265 | } 266 | 267 | /** 268 | * Combines `shares` to reconstruct the secret. 269 | * 270 | * @param shares A list of shares to reconstruct the secret from. Must be at least 2 and at most 255. 271 | * @returns The reconstructed secret. 272 | */ 273 | export async function combine(shares: Uint8Array[]): Promise { 274 | // Shares must be an array with length in the range [2, 256) 275 | AssertArgument.instanceOf(shares, Array, 'shares must be an Array'); 276 | AssertArgument.inRange( 277 | shares.length, 278 | 2, 279 | 256, 280 | 'shares must have at least 2 and at most 255 elements', 281 | ); 282 | 283 | // Shares must be a Uint8Array with at least 2 bytes and all shares must have the same byte length. 284 | const share1 = shares[0]!; 285 | AssertArgument.instanceOf(share1, Uint8Array, 'each share must be a Uint8Array'); 286 | for (const share of shares) { 287 | AssertArgument.instanceOf(share, Uint8Array, 'each share must be a Uint8Array'); 288 | AssertArgument.greaterThanOrEqualTo(share.byteLength, 2, 'each share must be at least 2 bytes'); 289 | AssertArgument.equalTo( 290 | share.byteLength, 291 | share1.byteLength, 292 | 'all shares must have the same byte length', 293 | ); 294 | } 295 | 296 | const sharesLength = shares.length; 297 | const shareLength = share1.byteLength; 298 | 299 | // This will be our reconstructed secret 300 | const secretLength = shareLength - 1; 301 | const secret = new Uint8Array(secretLength); 302 | 303 | const xSamples = new Uint8Array(sharesLength); 304 | const ySamples = new Uint8Array(sharesLength); 305 | 306 | const samples: Set = new Set(); 307 | for (let i = 0; i < sharesLength; i++) { 308 | const share = shares[i]!; 309 | const sample = share[shareLength - 1]!; 310 | 311 | // The last byte of each share should be a unique value between 1-255 inclusive. 312 | if (samples.has(sample)) { 313 | throw new Error('shares must contain unique values but a duplicate was found'); 314 | } 315 | 316 | samples.add(sample); 317 | xSamples[i] = sample; 318 | } 319 | 320 | // Reconstruct each byte 321 | for (let i = 0; i < secretLength; i++) { 322 | // Set the y value for each sample 323 | for (let j = 0; j < sharesLength; ++j) { 324 | ySamples[j] = shares[j]![i]!; 325 | } 326 | 327 | // Interpolate the polynomial and compute the value at 0 328 | secret[i] = interpolatePolynomial(xSamples, ySamples, 0); 329 | } 330 | 331 | return secret; 332 | } 333 | -------------------------------------------------------------------------------- /test/index.test.js: -------------------------------------------------------------------------------- 1 | const {split, combine} = require('../'); 2 | 3 | describe('shamir-secret-sharing', () => { 4 | const secret = new Uint8Array([0x73, 0x65, 0x63, 0x72, 0x65, 0x74]); 5 | 6 | it('cannot split with invalid arguments', async () => { 7 | const secretWrongType = split([0x73, 0x65, 0x63, 0x72, 0x65, 0x74], 3, 2); 8 | await expect(secretWrongType).rejects.toThrow(new TypeError('secret must be a Uint8Array')); 9 | 10 | const emptySecret = split(new Uint8Array(0), 3, 2); 11 | await expect(emptySecret).rejects.toThrow(new Error('secret cannot be empty')); 12 | 13 | const sharesWrongType = split(secret, '3', 2); 14 | await expect(sharesWrongType).rejects.toThrow(new TypeError('shares must be a number')); 15 | 16 | const sharesLT2 = split(secret, 1, 2); 17 | await expect(sharesLT2).rejects.toThrow( 18 | new RangeError('shares must be at least 2 and at most 255'), 19 | ); 20 | 21 | const sharesGT255 = split(secret, 256, 2); 22 | await expect(sharesGT255).rejects.toThrow( 23 | new RangeError('shares must be at least 2 and at most 255'), 24 | ); 25 | 26 | const thresholdWrongType = split(secret, 3, '2'); 27 | await expect(thresholdWrongType).rejects.toThrow(new TypeError('threshold must be a number')); 28 | 29 | const thresholdLT2 = split(secret, 2, 1); 30 | await expect(thresholdLT2).rejects.toThrow( 31 | new RangeError('threshold must be at least 2 and at most 255'), 32 | ); 33 | 34 | const thresholdGT255 = split(secret, 2, 256); 35 | await expect(thresholdGT255).rejects.toThrow( 36 | new RangeError('threshold must be at least 2 and at most 255'), 37 | ); 38 | 39 | const thresholdGTShares = split(secret, 3, 4); 40 | await expect(thresholdGTShares).rejects.toThrow( 41 | new Error('shares cannot be less than threshold'), 42 | ); 43 | }); 44 | 45 | it('cannot combine with invalid arguments', async () => { 46 | const bogusShare1 = new Uint8Array([0xff, 0x23]); 47 | const bogusShare2 = new Uint8Array([0xc1, 0xa7, 0x04]); 48 | 49 | const sharesWrongType = combine(bogusShare1, bogusShare2); 50 | await expect(sharesWrongType).rejects.toThrow(new TypeError('shares must be an Array')); 51 | 52 | const sharesWrongMinLength = combine([bogusShare1]); 53 | await expect(sharesWrongMinLength).rejects.toThrow( 54 | new TypeError('shares must have at least 2 and at most 255 elements'), 55 | ); 56 | 57 | const sharesWrongMaxLength = combine(new Array(256).fill(new Uint8Array(2))); 58 | await expect(sharesWrongMaxLength).rejects.toThrow( 59 | new TypeError('shares must have at least 2 and at most 255 elements'), 60 | ); 61 | 62 | const shareWrongType = combine([bogusShare1, 'bogusShare2']); 63 | await expect(shareWrongType).rejects.toThrow(new TypeError('each share must be a Uint8Array')); 64 | 65 | const shareWrongMinLength = combine([new Uint8Array(0), bogusShare2]); 66 | await expect(shareWrongMinLength).rejects.toThrow( 67 | new TypeError('each share must be at least 2 bytes'), 68 | ); 69 | 70 | const shareLengthMismatch = combine([bogusShare1, bogusShare2]); 71 | await expect(shareLengthMismatch).rejects.toThrow( 72 | new TypeError('all shares must have the same byte length'), 73 | ); 74 | 75 | const shareDuplicates = combine([bogusShare2, bogusShare2]); 76 | await expect(shareDuplicates).rejects.toThrow( 77 | new TypeError('shares must contain unique values but a duplicate was found'), 78 | ); 79 | }); 80 | 81 | it('can split a secret into multiple shares', async () => { 82 | const shares = await split(secret, 3, 2); 83 | expect(shares.length).toBe(3); 84 | 85 | const [a, b, c] = shares; 86 | expect(a).toBeInstanceOf(Uint8Array); 87 | expect(a.byteLength).toBe(secret.byteLength + 1); 88 | expect(b).toBeInstanceOf(Uint8Array); 89 | expect(b.byteLength).toBe(secret.byteLength + 1); 90 | expect(c).toBeInstanceOf(Uint8Array); 91 | expect(c.byteLength).toBe(secret.byteLength + 1); 92 | 93 | const reconstructed = await combine([a, c]); 94 | expect(reconstructed).toEqual(secret); 95 | }); 96 | 97 | it('can split a 1 byte secret', async () => { 98 | const oneByteSecret = new Uint8Array([0x33]); 99 | 100 | const shares = await split(oneByteSecret, 3, 2); 101 | expect(shares.length).toBe(3); 102 | 103 | const [a, b, c] = shares; 104 | expect(a.byteLength).toBe(2); 105 | expect(b.byteLength).toBe(2); 106 | expect(c.byteLength).toBe(2); 107 | 108 | const reconstructed = await combine([a, b]); 109 | expect(reconstructed).toEqual(oneByteSecret); 110 | }); 111 | 112 | it('can require all shares to reconstruct', async () => { 113 | const shares = await split(secret, 2, 2); 114 | expect(shares.length).toBe(2); 115 | await expect(combine(shares)).resolves.toEqual(secret); 116 | }); 117 | 118 | it('can combine using any combination of shares that meets the given threshold', async () => { 119 | const shares = await split(secret, 5, 3); 120 | expect(shares.length).toBe(5); 121 | 122 | // Test combining all permutations of 3 shares 123 | for (let i = 0; i < 5; i++) { 124 | expect(shares[i]).toBeInstanceOf(Uint8Array); 125 | expect(shares[i].byteLength).toBe(secret.byteLength + 1); 126 | for (let j = 0; j < 5; j++) { 127 | if (j === i) { 128 | continue; 129 | } 130 | for (let k = 0; k < 5; k++) { 131 | if (k === i || k === j) { 132 | continue; 133 | } 134 | const reconstructed = combine([shares[i], shares[j], shares[k]]); 135 | await expect(reconstructed).resolves.toEqual(secret); 136 | } 137 | } 138 | } 139 | }); 140 | }); 141 | -------------------------------------------------------------------------------- /tsconfig.esm.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "strict": true, 4 | "target": "es2020", 5 | "module": "es6", 6 | "moduleResolution": "node", 7 | "outDir": "esm", 8 | "noImplicitAny": true, 9 | "sourceMap": true, 10 | "inlineSources": false, 11 | "noUnusedLocals": true, 12 | "baseUrl": ".", 13 | "paths": { 14 | "shamir-secret-sharing/csprng": ["src/csprng"], 15 | }, 16 | }, 17 | "include": ["src"], 18 | "exclude": ["node_modules"] 19 | } -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "strict": true, 4 | "declaration": true, 5 | "target": "es2020", 6 | "module": "commonjs", 7 | "moduleResolution": "node", 8 | "outDir": ".", 9 | "noImplicitAny": true, 10 | "sourceMap": true, 11 | "inlineSources": false, 12 | "noUnusedLocals": true, 13 | "baseUrl": ".", 14 | "paths": { 15 | "shamir-secret-sharing/csprng": ["src/csprng"], 16 | }, 17 | }, 18 | "include": ["src"], 19 | "exclude": ["node_modules"] 20 | } --------------------------------------------------------------------------------