1
0
Fork 0
mirror of https://github.com/iancoleman/shamir.git synced 2025-11-18 00:50:59 +00:00
shamir/shamir-standalone.html

2053 lines
60 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Shamir Secret Sharing Scheme</title>
<style>/*
! tailwindcss v3.4.3 | MIT License | https://tailwindcss.com
*/
/*
1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4)
2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116)
*/
*,
::before,
::after {
box-sizing: border-box;
/* 1 */
border-width: 0;
/* 2 */
border-style: solid;
/* 2 */
border-color: #e5e7eb;
/* 2 */
}
::before,
::after {
--tw-content: '';
}
/*
1. Use a consistent sensible line-height in all browsers.
2. Prevent adjustments of font size after orientation changes in iOS.
3. Use a more readable tab size.
4. Use the user's configured `sans` font-family by default.
5. Use the user's configured `sans` font-feature-settings by default.
6. Use the user's configured `sans` font-variation-settings by default.
7. Disable tap highlights on iOS
*/
html,
:host {
line-height: 1.5;
/* 1 */
-webkit-text-size-adjust: 100%;
/* 2 */
-moz-tab-size: 4;
/* 3 */
-o-tab-size: 4;
tab-size: 4;
/* 3 */
font-family: sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
/* 4 */
font-feature-settings: normal;
/* 5 */
font-variation-settings: normal;
/* 6 */
-webkit-tap-highlight-color: transparent;
/* 7 */
}
/*
1. Remove the margin in all browsers.
2. Inherit line-height from `html` so users can set them as a class directly on the `html` element.
*/
body {
margin: 0;
/* 1 */
line-height: inherit;
/* 2 */
}
/*
1. Add the correct height in Firefox.
2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655)
3. Ensure horizontal rules are visible by default.
*/
hr {
height: 0;
/* 1 */
color: inherit;
/* 2 */
border-top-width: 1px;
/* 3 */
}
/*
Add the correct text decoration in Chrome, Edge, and Safari.
*/
abbr:where([title]) {
-webkit-text-decoration: underline dotted;
text-decoration: underline dotted;
}
/*
Remove the default font size and weight for headings.
*/
h1,
h2,
h3,
h4,
h5,
h6 {
font-size: inherit;
font-weight: inherit;
}
/*
Reset links to optimize for opt-in styling instead of opt-out.
*/
a {
color: inherit;
text-decoration: inherit;
}
/*
Add the correct font weight in Edge and Safari.
*/
b,
strong {
font-weight: bolder;
}
/*
1. Use the user's configured `mono` font-family by default.
2. Use the user's configured `mono` font-feature-settings by default.
3. Use the user's configured `mono` font-variation-settings by default.
4. Correct the odd `em` font sizing in all browsers.
*/
code,
kbd,
samp,
pre {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
/* 1 */
font-feature-settings: normal;
/* 2 */
font-variation-settings: normal;
/* 3 */
font-size: 1em;
/* 4 */
}
/*
Add the correct font size in all browsers.
*/
small {
font-size: 80%;
}
/*
Prevent `sub` and `sup` elements from affecting the line height in all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
/*
1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297)
2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016)
3. Remove gaps between table borders by default.
*/
table {
text-indent: 0;
/* 1 */
border-color: inherit;
/* 2 */
border-collapse: collapse;
/* 3 */
}
/*
1. Change the font styles in all browsers.
2. Remove the margin in Firefox and Safari.
3. Remove default padding in all browsers.
*/
button,
input,
optgroup,
select,
textarea {
font-family: inherit;
/* 1 */
font-feature-settings: inherit;
/* 1 */
font-variation-settings: inherit;
/* 1 */
font-size: 100%;
/* 1 */
font-weight: inherit;
/* 1 */
line-height: inherit;
/* 1 */
letter-spacing: inherit;
/* 1 */
color: inherit;
/* 1 */
margin: 0;
/* 2 */
padding: 0;
/* 3 */
}
/*
Remove the inheritance of text transform in Edge and Firefox.
*/
button,
select {
text-transform: none;
}
/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Remove default button styles.
*/
button,
input:where([type='button']),
input:where([type='reset']),
input:where([type='submit']) {
-webkit-appearance: button;
/* 1 */
background-color: transparent;
/* 2 */
background-image: none;
/* 2 */
}
/*
Use the modern Firefox focus style for all focusable elements.
*/
:-moz-focusring {
outline: auto;
}
/*
Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737)
*/
:-moz-ui-invalid {
box-shadow: none;
}
/*
Add the correct vertical alignment in Chrome and Firefox.
*/
progress {
vertical-align: baseline;
}
/*
Correct the cursor style of increment and decrement buttons in Safari.
*/
::-webkit-inner-spin-button,
::-webkit-outer-spin-button {
height: auto;
}
/*
1. Correct the odd appearance in Chrome and Safari.
2. Correct the outline style in Safari.
*/
[type='search'] {
-webkit-appearance: textfield;
/* 1 */
outline-offset: -2px;
/* 2 */
}
/*
Remove the inner padding in Chrome and Safari on macOS.
*/
::-webkit-search-decoration {
-webkit-appearance: none;
}
/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Change font properties to `inherit` in Safari.
*/
::-webkit-file-upload-button {
-webkit-appearance: button;
/* 1 */
font: inherit;
/* 2 */
}
/*
Add the correct display in Chrome and Safari.
*/
summary {
display: list-item;
}
/*
Removes the default spacing and border for appropriate elements.
*/
blockquote,
dl,
dd,
h1,
h2,
h3,
h4,
h5,
h6,
hr,
figure,
p,
pre {
margin: 0;
}
fieldset {
margin: 0;
padding: 0;
}
legend {
padding: 0;
}
ol,
ul,
menu {
list-style: none;
margin: 0;
padding: 0;
}
/*
Reset default styling for dialogs.
*/
dialog {
padding: 0;
}
/*
Prevent resizing textareas horizontally by default.
*/
textarea {
resize: vertical;
}
/*
1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300)
2. Set the default placeholder color to the user's configured gray 400 color.
*/
input::-moz-placeholder, textarea::-moz-placeholder {
opacity: 1;
/* 1 */
color: #9ca3af;
/* 2 */
}
input::placeholder,
textarea::placeholder {
opacity: 1;
/* 1 */
color: #9ca3af;
/* 2 */
}
/*
Set the default cursor for buttons.
*/
button,
[role="button"] {
cursor: pointer;
}
/*
Make sure disabled buttons don't get the pointer cursor.
*/
:disabled {
cursor: default;
}
/*
1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14)
2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210)
This can trigger a poorly considered lint error in some tools but is included by design.
*/
img,
svg,
video,
canvas,
audio,
iframe,
embed,
object {
display: block;
/* 1 */
vertical-align: middle;
/* 2 */
}
/*
Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14)
*/
img,
video {
max-width: 100%;
height: auto;
}
/* Make elements with the HTML hidden attribute stay hidden by default */
[hidden] {
display: none;
}
*, ::before, ::after {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-gradient-from-position: ;
--tw-gradient-via-position: ;
--tw-gradient-to-position: ;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
--tw-contain-size: ;
--tw-contain-layout: ;
--tw-contain-paint: ;
--tw-contain-style: ;
}
::backdrop {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-gradient-from-position: ;
--tw-gradient-via-position: ;
--tw-gradient-to-position: ;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
--tw-contain-size: ;
--tw-contain-layout: ;
--tw-contain-paint: ;
--tw-contain-style: ;
}
.container {
width: 100%;
}
@media (min-width: 640px) {
.container {
max-width: 640px;
}
}
@media (min-width: 768px) {
.container {
max-width: 768px;
}
}
@media (min-width: 1024px) {
.container {
max-width: 1024px;
}
}
@media (min-width: 1280px) {
.container {
max-width: 1280px;
}
}
@media (min-width: 1536px) {
.container {
max-width: 1536px;
}
}
.relative {
position: relative;
}
.-mx-3 {
margin-left: -0.75rem;
margin-right: -0.75rem;
}
.my-2 {
margin-top: 0.5rem;
margin-bottom: 0.5rem;
}
.my-3 {
margin-top: 0.75rem;
margin-bottom: 0.75rem;
}
.my-4 {
margin-top: 1rem;
margin-bottom: 1rem;
}
.mb-0 {
margin-bottom: 0px;
}
.mb-1 {
margin-bottom: 0.25rem;
}
.mb-2 {
margin-bottom: 0.5rem;
}
.mb-3 {
margin-bottom: 0.75rem;
}
.mt-4 {
margin-top: 1rem;
}
.flex {
display: flex;
}
.contents {
display: contents;
}
.hidden {
display: none;
}
.w-full {
width: 100%;
}
.max-w-full {
max-width: 100%;
}
.cursor-pointer {
cursor: pointer;
}
.gap-2 {
gap: 0.5rem;
}
.overflow-hidden {
overflow: hidden;
}
.break-words {
overflow-wrap: break-word;
}
.rounded-lg {
border-radius: 0.5rem;
}
.border {
border-width: 1px;
}
.border-0 {
border-width: 0px;
}
.border-b {
border-bottom-width: 1px;
}
.border-solid {
border-style: solid;
}
.border-red-200 {
--tw-border-opacity: 1;
border-color: rgb(254 202 202 / var(--tw-border-opacity));
}
.border-zinc-200 {
--tw-border-opacity: 1;
border-color: rgb(228 228 231 / var(--tw-border-opacity));
}
.bg-red-100 {
--tw-bg-opacity: 1;
background-color: rgb(254 226 226 / var(--tw-bg-opacity));
}
.p-3 {
padding: 0.75rem;
}
.px-12 {
padding-left: 3rem;
padding-right: 3rem;
}
.px-2 {
padding-left: 0.5rem;
padding-right: 0.5rem;
}
.px-5 {
padding-left: 1.25rem;
padding-right: 1.25rem;
}
.py-2 {
padding-top: 0.5rem;
padding-bottom: 0.5rem;
}
.py-2\.5 {
padding-top: 0.625rem;
padding-bottom: 0.625rem;
}
.font-sans {
font-family: sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
}
.text-3xl {
font-size: 1.875rem;
line-height: 2.25rem;
}
.text-4xl {
font-size: 2.25rem;
line-height: 2.5rem;
}
.text-sm {
font-size: 0.875rem;
line-height: 1.25rem;
}
.font-semibold {
font-weight: 600;
}
.leading-8 {
line-height: 2rem;
}
.text-\[\#333\] {
--tw-text-opacity: 1;
color: rgb(51 51 51 / var(--tw-text-opacity));
}
.text-red-700 {
--tw-text-opacity: 1;
color: rgb(185 28 28 / var(--tw-text-opacity));
}
.text-sky-600 {
--tw-text-opacity: 1;
color: rgb(2 132 199 / var(--tw-text-opacity));
}
.underline {
text-decoration-line: underline;
}
input[type="number"] {
display: inline-block;
width: 70px;
}
.active-tab::after {
position: absolute;
width: 100%;
border-radius: 0.375rem;
--tw-bg-opacity: 1;
background-color: rgb(234 88 12 / var(--tw-bg-opacity));
/* background: #f78166; */
bottom: calc(50% - 22px);
content: "";
height: 2px;
right: 50%;
transform: translate(50%, -50%);
z-index: 1;
}
.form-control {
display: block;
border-radius: 0.375rem;
border-width: 1px;
border-style: solid;
--tw-border-opacity: 1;
border-color: rgb(212 212 216 / var(--tw-border-opacity));
--tw-bg-opacity: 1;
background-color: rgb(255 255 255 / var(--tw-bg-opacity));
padding-left: 0.75rem;
padding-right: 0.75rem;
padding-top: 0.5rem;
padding-bottom: 0.5rem;
font-size: 1rem;
line-height: 1.5rem;
--tw-text-opacity: 1;
color: rgb(17 24 39 / var(--tw-text-opacity));
transition-property: color, background-color, border-color, text-decoration-color, fill, stroke;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 150ms;
}
.form-control::-moz-placeholder {
--tw-text-opacity: 1;
color: rgb(156 163 175 / var(--tw-text-opacity));
}
.form-control::placeholder {
--tw-text-opacity: 1;
color: rgb(156 163 175 / var(--tw-text-opacity));
}
.form-control:focus {
--tw-border-opacity: 1;
border-color: rgb(165 180 252 / var(--tw-border-opacity));
outline: 2px solid transparent;
outline-offset: 2px;
--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color);
box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);
--tw-ring-color: rgb(199 210 254 / var(--tw-ring-opacity));
--tw-ring-opacity: 0.5;
}
textarea.form-control {
width: 100%;
resize: vertical;
}
.odd\:bg-\[\#f4f4f3\]:nth-child(odd) {
--tw-bg-opacity: 1;
background-color: rgb(244 244 243 / var(--tw-bg-opacity));
}
.even\:bg-\[\#e9e8e6\]:nth-child(even) {
--tw-bg-opacity: 1;
background-color: rgb(233 232 230 / var(--tw-bg-opacity));
}
.hover\:bg-zinc-100:hover {
--tw-bg-opacity: 1;
background-color: rgb(244 244 245 / var(--tw-bg-opacity));
}
.hover\:text-sky-800:hover {
--tw-text-opacity: 1;
color: rgb(7 89 133 / var(--tw-text-opacity));
}
</style>
<meta content="Shamir Secret Sharing Scheme tool" name="description"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport" />
<meta content="Ian Coleman" name="author" />
</head>
<body class="font-sans text-[#333]">
<div class="container px-12 my-4">
<div class="-mx-3 flex mb-3">
<div class="px-5">
<h1 class="text-4xl mb-3">Shamir Secret Sharing Scheme</h1>
<p class="mb-0">Split your secret into parts which can be combined back into the original secret using some or all of the parts.</p>
</div>
</div>
<p id="error-message" class="text-red-700 my-3 w-full p-3 bg-red-100 rounded-lg hidden border-red-200 border"></p>
<div class="w-full flex gap-2 border-b border-zinc-200 border-solid border-0">
<div id="split-secret-tab" role="tab" class="px-2 leading-8 mb-1 text-sm font-semibold cursor-pointer hover:bg-zinc-100 rounded-lg relative active-tab">Split Secret</div>
<div id="combine-secret-tab" role="tab" class="px-2 leading-8 mb-1 text-sm cursor-pointer hover:bg-zinc-100 rounded-lg relative">Combine Secret</div>
</div>
<div id="split-secret" class="w-full my-4">
<!-- <h2>Split</h2> -->
<div class="mb-2">
Require
<input id="required-parts" class="form-control" type="number" value="3" min="2" max="255">
parts from
<input id="total-parts" class="form-control" type="number" value="5" min="2" max="255">
to reconstruct the following secret:
</div>
<textarea id="secret" class="form-control mb-3" rows=10 placeholder="Enter your secret here"></textarea>
<h2 class="text-3xl mb-3">Usage</h2>
<p class="mb-1">Double click each part below to select the content for that part. Copy and paste the content for each part into <span id="distributesize">5</span> individual files on your computer.</p>
<p class="mb-1">Distribute one file to each person in your group.</p>
<p class="mb-1">If <span id="recreatesize">3</span> of those people can combine the contents of their file using this page, they can view the secret.</p>
<p class="mb-3">Remember to delete the parts from your computer once you're finished. If you use a rubbish bin for deleted files, also remove them from the rubbish bin.</p>
<h2 class="text-3xl my-3">Parts</h2>
<ol id="generated" class="max-w-full break-words rounded-lg overflow-hidden">
<li>Enter your secret above.</li>
</ol>
</div>
<div id="combine-secret" class="hidden w-full my-4">
<!-- <h2>Combine</h2> -->
<p class="my-2 mb-2">
Enter the secrets, one per line
</p>
<textarea id="parts" class="form-control mb-3" rows=10></textarea>
<h2 class="text-3xl mb-3">Result</h2>
<p id="combined">Enter your parts above.</p>
</div>
<hr>
<div class="mt-4">
<h2 class="text-3xl mb-2">Sources</h2>
<p class="mb-1"><a href="https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing" class="text-sky-600 underline hover:text-sky-800">Wikipedia entry</a> for shamir secret sharing scheme.</p>
<p class="mb-1">This project is 100% open-source. <a href="https://github.com/iancoleman/shamir" class="text-sky-600 underline hover:text-sky-800">View the project source code on GitHub</a></p>
<p class="mb-1"><a href="https://github.com/grempe/secrets.js" class="text-sky-600 underline hover:text-sky-800">Built with the SSSS javascript library by amper5and and Glenn Rempe</a></p>
<p><a href="https://tailwindcss.com/" class="text-sky-600 underline hover:text-sky-800">Styled with Tailwind</a></p>
<h2 class="text-3xl mb-2 mt-4">Offline Usage</h2>
<p class="mb-1">This tool has been designed to be used offline.</p>
<p class="mb-1">In your browser, select file save-as, and save this page as a file.</p>
<p>Double-click that file to open it in a browser on any offline computer.</p>
</div>
</div>
<script>// @preserve author Alexander Stetsyuk
// @preserve author Glenn Rempe <glenn@rempe.us>
// @license MIT
/*jslint passfail: false, bitwise: true, nomen: true, plusplus: true, todo: false, maxerr: 1000 */
/*global define, require, module, exports, window, Uint32Array, sjcl */
// eslint : http://eslint.org/docs/configuring/
/*eslint-env node, browser, jasmine, sjcl */
/*eslint no-underscore-dangle:0 */
// UMD (Universal Module Definition)
// Uses Node, AMD or browser globals to create a module. This module creates
// a global even when AMD is used. This is useful if you have some scripts
// that are loaded by an AMD loader, but they still want access to globals.
// See : https://github.com/umdjs/umd
// See : https://github.com/umdjs/umd/blob/master/returnExportsGlobal.js
//
(function (root, factory) {
"use strict";
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define([], function () {
/*eslint-disable no-return-assign */
return (root.secrets = factory());
/*eslint-enable no-return-assign */
});
} else if (typeof exports === "object") {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require("crypto"));
} else {
// Browser globals (root is window)
root.secrets = factory(root.crypto);
}
}(this, function (crypto) {
"use strict";
var defaults,
config,
preGenPadding,
runCSPRNGTest,
sjclParanoia,
CSPRNGTypes;
function reset() {
defaults = {
bits: 8, // default number of bits
radix: 16, // work with HEX by default
minBits: 3,
maxBits: 20, // this permits 1,048,575 shares, though going this high is NOT recommended in JS!
bytesPerChar: 2,
maxBytesPerChar: 6, // Math.pow(256,7) > Math.pow(2,53)
// Primitive polynomials (in decimal form) for Galois Fields GF(2^n), for 2 <= n <= 30
// The index of each term in the array corresponds to the n for that polynomial
// i.e. to get the polynomial for n=16, use primitivePolynomials[16]
primitivePolynomials: [null, null, 1, 3, 3, 5, 3, 3, 29, 17, 9, 5, 83, 27, 43, 3, 45, 9, 39, 39, 9, 5, 3, 33, 27, 9, 71, 39, 9, 5, 83]
};
config = {};
preGenPadding = new Array(1024).join("0"); // Pre-generate a string of 1024 0's for use by padLeft().
runCSPRNGTest = true;
sjclParanoia = 10;
// WARNING : Never use 'testRandom' except for testing.
CSPRNGTypes = ["nodeCryptoRandomBytes", "browserCryptoGetRandomValues", "browserSJCLRandom", "testRandom"];
}
function isSetRNG() {
if (config && config.rng && typeof config.rng === "function") {
return true;
}
return false;
}
// Pads a string `str` with zeros on the left so that its length is a multiple of `bits`
function padLeft(str, multipleOfBits) {
var missing;
if (multipleOfBits === 0 || multipleOfBits === 1) {
return str;
}
if (multipleOfBits && multipleOfBits > 1024) {
throw new Error("Padding must be multiples of no larger than 1024 bits.");
}
multipleOfBits = multipleOfBits || config.bits;
if (str) {
missing = str.length % multipleOfBits;
}
if (missing) {
return (preGenPadding + str).slice(-(multipleOfBits - missing + str.length));
}
return str;
}
function hex2bin(str) {
var bin = "",
num,
i;
for (i = str.length - 1; i >= 0; i--) {
num = parseInt(str[i], 16);
if (isNaN(num)) {
throw new Error("Invalid hex character.");
}
bin = padLeft(num.toString(2), 4) + bin;
}
return bin;
}
function bin2hex(str) {
var hex = "",
num,
i;
str = padLeft(str, 4);
for (i = str.length; i >= 4; i -= 4) {
num = parseInt(str.slice(i - 4, i), 2);
if (isNaN(num)) {
throw new Error("Invalid binary character.");
}
hex = num.toString(16) + hex;
}
return hex;
}
// Browser supports crypto.getRandomValues()
function hasCryptoGetRandomValues() {
if (crypto &&
typeof crypto === "object" &&
(typeof crypto.getRandomValues === "function" || typeof crypto.getRandomValues === "object") &&
(typeof Uint32Array === "function" || typeof Uint32Array === "object")) {
return true;
}
return false;
}
// Node.js support for crypto.randomBytes()
function hasCryptoRandomBytes() {
if (typeof crypto === "object" &&
typeof crypto.randomBytes === "function") {
return true;
}
return false;
}
// Stanford Javascript Crypto Library Support
function hasSJCL() {
if (typeof sjcl === "object" &&
typeof sjcl.random === "object") {
return true;
}
return false;
}
// Returns a pseudo-random number generator of the form function(bits){}
// which should output a random string of 1's and 0's of length `bits`.
// `type` (Optional) : A string representing the CSPRNG that you want to
// force to be loaded, overriding feature detection. Can be one of:
// "nodeCryptoRandomBytes"
// "browserCryptoGetRandomValues"
// "browserSJCLRandom"
//
function getRNG(type) {
function construct(bits, arr, radix, size) {
var i = 0,
len,
str = "",
parsedInt;
if (arr) {
len = arr.length - 1;
}
while (i < len || (str.length < bits)) {
// convert any negative nums to positive with Math.abs()
parsedInt = Math.abs(parseInt(arr[i], radix));
str = str + padLeft(parsedInt.toString(2), size);
i++;
}
str = str.substr(-bits);
// return null so this result can be re-processed if the result is all 0's.
if ((str.match(/0/g) || []).length === str.length) {
return null;
}
return str;
}
// Node.js : crypto.randomBytes()
// Note : Node.js and crypto.randomBytes() uses the OpenSSL RAND_bytes() function for its CSPRNG.
// Node.js will need to have been compiled with OpenSSL for this to work.
// See : https://github.com/joyent/node/blob/d8baf8a2a4481940bfed0196308ae6189ca18eee/src/node_crypto.cc#L4696
// See : https://www.openssl.org/docs/crypto/rand.html
function nodeCryptoRandomBytes(bits) {
var buf,
bytes,
radix,
size,
str = null;
radix = 16;
size = 4;
bytes = Math.ceil(bits / 8);
while (str === null) {
buf = crypto.randomBytes(bytes);
str = construct(bits, buf.toString("hex"), radix, size);
}
return str;
}
// Browser : crypto.getRandomValues()
// See : https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#dfn-Crypto
// See : https://developer.mozilla.org/en-US/docs/Web/API/RandomSource/getRandomValues
// Supported Browsers : http://caniuse.com/#search=crypto.getRandomValues
function browserCryptoGetRandomValues(bits) {
var elems,
radix,
size,
str = null;
radix = 10;
size = 32;
elems = Math.ceil(bits / 32);
while (str === null) {
str = construct(bits, crypto.getRandomValues(new Uint32Array(elems)), radix, size);
}
return str;
}
// Browser SJCL : If the Stanford Javascript Crypto Library (SJCL) is loaded in the browser
// then use it as a fallback CSPRNG when crypto.getRandomValues() is not available.
// It may require some time and mouse movements to be fully seeded. Uses a modified version
// of the Fortuna RNG.
// See : https://bitwiseshiftleft.github.io/sjcl/
function browserSJCLRandom(bits) {
var elems,
radix,
size,
str = null;
radix = 10;
size = 32;
elems = Math.ceil(bits / 32);
if(sjcl.random.isReady(sjclParanoia)) {
str = construct(bits, sjcl.random.randomWords(elems, sjclParanoia), radix, size);
} else {
throw new Error("SJCL isn't finished seeding the RNG yet.");
}
return str;
}
// /////////////////////////////////////////////////////////////
// WARNING : DO NOT USE. For testing purposes only.
// /////////////////////////////////////////////////////////////
// This function will return repeatable non-random test bits. Can be used
// for testing only. Node.js does not return proper random bytes
// when run within a PhantomJS container.
function testRandom(bits) {
var arr,
elems,
int,
radix,
size,
str = null;
radix = 10;
size = 32;
elems = Math.ceil(bits / 32);
int = 123456789;
arr = new Uint32Array(elems);
// Fill every element of the Uint32Array with the same int.
for (var i = 0; i < arr.length; i++) {
arr[i] = int;
}
while (str === null) {
str = construct(bits, arr, radix, size);
}
return str;
}
// Return a random generator function for browsers that support HTML5
// crypto.getRandomValues(), Node.js compiled with OpenSSL support.
// or the Stanford Javascript Crypto Library Fortuna RNG.
// WARNING : NEVER use testRandom outside of a testing context. Totally non-random!
if (type && type === "testRandom") {
config.typeCSPRNG = type;
return testRandom;
} else if (type && type === "nodeCryptoRandomBytes") {
config.typeCSPRNG = type;
return nodeCryptoRandomBytes;
} else if (type && type === "browserCryptoGetRandomValues") {
config.typeCSPRNG = type;
return browserCryptoGetRandomValues;
} else if (type && type === "browserSJCLRandom") {
runCSPRNGTest = false;
config.typeCSPRNG = type;
return browserSJCLRandom;
} else if (hasCryptoRandomBytes()) {
config.typeCSPRNG = "nodeCryptoRandomBytes";
return nodeCryptoRandomBytes;
} else if (hasCryptoGetRandomValues()) {
config.typeCSPRNG = "browserCryptoGetRandomValues";
return browserCryptoGetRandomValues;
} else if (hasSJCL()) {
runCSPRNGTest = false;
config.typeCSPRNG = "browserSJCLRandom";
return browserSJCLRandom;
}
}
// Splits a number string `bits`-length segments, after first
// optionally zero-padding it to a length that is a multiple of `padLength.
// Returns array of integers (each less than 2^bits-1), with each element
// representing a `bits`-length segment of the input string from right to left,
// i.e. parts[0] represents the right-most `bits`-length segment of the input string.
function splitNumStringToIntArray(str, padLength) {
var parts = [],
i;
if (padLength) {
str = padLeft(str, padLength);
}
for (i = str.length; i > config.bits; i -= config.bits) {
parts.push(parseInt(str.slice(i - config.bits, i), 2));
}
parts.push(parseInt(str.slice(0, i), 2));
return parts;
}
// Polynomial evaluation at `x` using Horner's Method
// NOTE: fx=fx * x + coeff[i] -> exp(log(fx) + log(x)) + coeff[i],
// so if fx===0, just set fx to coeff[i] because
// using the exp/log form will result in incorrect value
function horner(x, coeffs) {
var logx = config.logs[x],
fx = 0,
i;
for (i = coeffs.length - 1; i >= 0; i--) {
if (fx !== 0) {
fx = config.exps[(logx + config.logs[fx]) % config.maxShares] ^ coeffs[i];
} else {
fx = coeffs[i];
}
}
return fx;
}
// Evaluate the Lagrange interpolation polynomial at x = `at`
// using x and y Arrays that are of the same length, with
// corresponding elements constituting points on the polynomial.
function lagrange(at, x, y) {
var sum = 0,
len,
product,
i,
j;
for (i = 0, len = x.length; i < len; i++) {
if (y[i]) {
product = config.logs[y[i]];
for (j = 0; j < len; j++) {
if (i !== j) {
if (at === x[j]) { // happens when computing a share that is in the list of shares used to compute it
product = -1; // fix for a zero product term, after which the sum should be sum^0 = sum, not sum^1
break;
}
product = (product + config.logs[at ^ x[j]] - config.logs[x[i] ^ x[j]] + config.maxShares) % config.maxShares; // to make sure it's not negative
}
}
// though exps[-1] === undefined and undefined ^ anything = anything in
// chrome, this behavior may not hold everywhere, so do the check
sum = product === -1 ? sum : sum ^ config.exps[product];
}
}
return sum;
}
// This is the basic polynomial generation and evaluation function
// for a `config.bits`-length secret (NOT an arbitrary length)
// Note: no error-checking at this stage! If `secret` is NOT
// a NUMBER less than 2^bits-1, the output will be incorrect!
function getShares(secret, numShares, threshold) {
var shares = [],
coeffs = [secret],
i,
len;
for (i = 1; i < threshold; i++) {
coeffs[i] = parseInt(config.rng(config.bits), 2);
}
for (i = 1, len = numShares + 1; i < len; i++) {
shares[i - 1] = {
x: i,
y: horner(i, coeffs)
};
}
return shares;
}
function constructPublicShareString(bits, id, data) {
var bitsBase36,
idHex,
idMax,
idPaddingLen,
newShareString;
id = parseInt(id, config.radix);
bits = parseInt(bits, 10) || config.bits;
bitsBase36 = bits.toString(36).toUpperCase();
idMax = Math.pow(2, bits) - 1;
idPaddingLen = idMax.toString(config.radix).length;
idHex = padLeft(id.toString(config.radix), idPaddingLen);
if (typeof id !== "number" || id % 1 !== 0 || id < 1 || id > idMax) {
throw new Error("Share id must be an integer between 1 and " + idMax + ", inclusive.");
}
newShareString = bitsBase36 + idHex + data;
return newShareString;
}
// EXPORTED FUNCTIONS
// //////////////////
var secrets = {
init: function (bits, rngType) {
var logs = [],
exps = [],
x = 1,
primitive,
i;
// reset all config back to initial state
reset();
if (bits && (typeof bits !== "number" || bits % 1 !== 0 || bits < defaults.minBits || bits > defaults.maxBits)) {
throw new Error("Number of bits must be an integer between " + defaults.minBits + " and " + defaults.maxBits + ", inclusive.");
}
if (rngType && CSPRNGTypes.indexOf(rngType) === -1) {
throw new Error("Invalid RNG type argument : '" + rngType + "'");
}
config.radix = defaults.radix;
config.bits = bits || defaults.bits;
config.size = Math.pow(2, config.bits);
config.maxShares = config.size - 1;
// Construct the exp and log tables for multiplication.
primitive = defaults.primitivePolynomials[config.bits];
for (i = 0; i < config.size; i++) {
exps[i] = x;
logs[x] = i;
x = x << 1; // Left shift assignment
if (x >= config.size) {
x = x ^ primitive; // Bitwise XOR assignment
x = x & config.maxShares; // Bitwise AND assignment
}
}
config.logs = logs;
config.exps = exps;
if (rngType) {
this.setRNG(rngType);
}
if (!isSetRNG()) {
this.setRNG();
}
// Setup SJCL and start collecting entropy from mouse movements
if (hasSJCL() && config.typeCSPRNG === "browserSJCLRandom") {
/*eslint-disable new-cap */
sjcl.random = new sjcl.prng(sjclParanoia);
/*eslint-enable new-cap */
// In a Browser
if (hasCryptoGetRandomValues()) {
// Collects entropy from browser mouse movement
// which obviously won't work in Node.js.
sjcl.random.startCollectors();
}
// see SJCL with browser or Node.js RNG if available.
this.seedRNG();
}
if (!isSetRNG() || !config.bits || !config.size || !config.maxShares || !config.logs || !config.exps || config.logs.length !== config.size || config.exps.length !== config.size) {
throw new Error("Initialization failed.");
}
},
// Pass in additional secure entropy, and an estimate of the bits of entropy
// provided, and a source name, and it will be used to seed the SJCL PRNG. This is
// useful since SJCL may take a while to be seeded since it depends on mouse
// movement and this can kickstart the generator almost immediately. SJCL will
// also continue to collect entropy from mouse movements after seeding.
//
// e.g. from random data sources like:
// https://api.random.org/json-rpc/1/
// https://entropy.ubuntu.com/?challenge=123
// https://qrng.anu.edu.au/API/api-demo.php
//
// See `examples/example_js_global.html` for sample usage with an
// external source of entropy.
seedRNG: function (data, estimatedEntropy, source) {
var bytes, rand;
estimatedEntropy = parseInt(estimatedEntropy, 10);
source = source || "seedRNG";
// Seed with browser RNG
if (hasSJCL() && hasCryptoGetRandomValues()) {
bytes = new Uint32Array(256);
rand = crypto.getRandomValues(bytes);
//console.log(rand);
sjcl.random.addEntropy(rand, 2048, "cryptoGetRandomValues");
}
// See with Node.js RNG (Async)
if (hasSJCL() && hasCryptoRandomBytes()) {
crypto.randomBytes(256, function(ex, buf) {
if (ex) { throw ex; }
//console.log("Have %d bytes of random data containing %s", buf.length, buf.toString('hex'));
sjcl.random.addEntropy(buf.toString("hex"), 2048, "cryptoRandomBytes");
});
}
if (hasSJCL() && data && estimatedEntropy && source && config.typeCSPRNG === "browserSJCLRandom") {
sjcl.random.addEntropy(data, estimatedEntropy, source);
}
},
// Evaluates the Lagrange interpolation polynomial at x=`at` for
// individual config.bits-length segments of each share in the `shares`
// Array. Each share is expressed in base `inputRadix`. The output
// is expressed in base `outputRadix'.
combine: function (shares, at) {
var i,
j,
len,
len2,
result = "",
setBits,
share,
splitShare,
x = [],
y = [];
at = at || 0;
for (i = 0, len = shares.length; i < len; i++) {
share = this.extractShareComponents(shares[i]);
// All shares must have the same bits settings.
if (setBits === undefined) {
setBits = share.bits;
} else if (share.bits !== setBits) {
throw new Error("Mismatched shares: Different bit settings.");
}
// Reset everything to the bit settings of the shares.
if (config.bits !== setBits) {
this.init(setBits);
}
// Proceed if this share.id is not already in the Array 'x' and
// then split each share's hex data into an Array of Integers,
// then 'rotate' those arrays where the first element of each row is converted to
// its own array, the second element of each to its own Array, and so on for all of the rest.
// Essentially zipping all of the shares together.
//
// e.g.
// [ 193, 186, 29, 150, 5, 120, 44, 46, 49, 59, 6, 1, 102, 98, 177, 196 ]
// [ 53, 105, 139, 49, 187, 240, 91, 92, 98, 118, 12, 2, 204, 196, 127, 149 ]
// [ 146, 211, 249, 167, 209, 136, 118, 114, 83, 77, 10, 3, 170, 166, 206, 81 ]
//
// becomes:
//
// [ [ 193, 53, 146 ],
// [ 186, 105, 211 ],
// [ 29, 139, 249 ],
// [ 150, 49, 167 ],
// [ 5, 187, 209 ],
// [ 120, 240, 136 ],
// [ 44, 91, 118 ],
// [ 46, 92, 114 ],
// [ 49, 98, 83 ],
// [ 59, 118, 77 ],
// [ 6, 12, 10 ],
// [ 1, 2, 3 ],
// [ 102, 204, 170 ],
// [ 98, 196, 166 ],
// [ 177, 127, 206 ],
// [ 196, 149, 81 ] ]
//
if (x.indexOf(share.id) === -1) {
x.push(share.id);
splitShare = splitNumStringToIntArray(hex2bin(share.data));
for (j = 0, len2 = splitShare.length; j < len2; j++) {
y[j] = y[j] || [];
y[j][x.length - 1] = splitShare[j];
}
}
}
// Extract the secret from the 'rotated' share data and return a
// string of Binary digits which represent the secret directly. or in the
// case of a newShare() return the binary string representing just that
// new share.
for (i = 0, len = y.length; i < len; i++) {
result = padLeft(lagrange(at, x, y[i]).toString(2)) + result;
}
// If 'at' is non-zero combine() was called from newShare(). In this
// case return the result (the new share data) directly.
//
// Otherwise find the first '1' which was added in the share() function as a padding marker
// and return only the data after the padding and the marker. Convert this Binary string
// to hex, which represents the final secret result (which can be converted from hex back
// to the original string in user space using `hex2str()`).
return bin2hex(at >= 1 ? result : result.slice(result.indexOf("1") + 1));
},
getConfig: function () {
var obj = {};
obj.radix = config.radix;
obj.bits = config.bits;
obj.maxShares = config.maxShares;
obj.hasCSPRNG = isSetRNG();
obj.typeCSPRNG = config.typeCSPRNG;
return obj;
},
// Given a public share, extract the bits (Integer), share ID (Integer), and share data (Hex)
// and return an Object containing those components.
extractShareComponents: function (share) {
var bits,
id,
idLen,
max,
obj = {},
regexStr,
shareComponents;
// Extract the first char which represents the bits in Base 36
bits = parseInt(share.substr(0, 1), 36);
if (bits && (typeof bits !== "number" || bits % 1 !== 0 || bits < defaults.minBits || bits > defaults.maxBits)) {
throw new Error("Invalid share : Number of bits must be an integer between " + defaults.minBits + " and " + defaults.maxBits + ", inclusive.");
}
// calc the max shares allowed for given bits
max = Math.pow(2, bits) - 1;
// Determine the ID length which is variable and based on the bit count.
idLen = (Math.pow(2, bits) - 1).toString(config.radix).length;
// Extract all the parts now that the segment sizes are known.
regexStr = "^([a-kA-K3-9]{1})([a-fA-F0-9]{" + idLen + "})([a-fA-F0-9]+)$";
shareComponents = new RegExp(regexStr).exec(share);
// The ID is a Hex number and needs to be converted to an Integer
if (shareComponents) {
id = parseInt(shareComponents[2], config.radix);
}
if (typeof id !== "number" || id % 1 !== 0 || id < 1 || id > max) {
throw new Error("Invalid share : Share id must be an integer between 1 and " + config.maxShares + ", inclusive.");
}
if (shareComponents && shareComponents[3]) {
obj.bits = bits;
obj.id = id;
obj.data = shareComponents[3];
return obj;
}
throw new Error("The share data provided is invalid : " + share);
},
// Set the PRNG to use. If no RNG function is supplied, pick a default using getRNG()
setRNG: function (rng) {
var errPrefix = "Random number generator is invalid ",
errSuffix = " Supply an CSPRNG of the form function(bits){} that returns a string containing 'bits' number of random 1's and 0's.";
if (rng && typeof rng === "string" && CSPRNGTypes.indexOf(rng) === -1) {
throw new Error("Invalid RNG type argument : '" + rng + "'");
}
// If RNG was not specified at all,
// try to pick one appropriate for this env.
if (!rng) {
rng = getRNG();
}
// If `rng` is a string, try to forcibly
// set the RNG to the type specified.
if (rng && typeof rng === "string") {
rng = getRNG(rng);
}
if (runCSPRNGTest) {
if (rng && typeof rng !== "function") {
throw new Error(errPrefix + "(Not a function)." + errSuffix);
}
if (rng && typeof rng(config.bits) !== "string") {
throw new Error(errPrefix + "(Output is not a string)." + errSuffix);
}
if (rng && !parseInt(rng(config.bits), 2)) {
throw new Error(errPrefix + "(Binary string output not parseable to an Integer)." + errSuffix);
}
if (rng && rng(config.bits).length > config.bits) {
throw new Error(errPrefix + "(Output length is greater than config.bits)." + errSuffix);
}
if (rng && rng(config.bits).length < config.bits) {
throw new Error(errPrefix + "(Output length is less than config.bits)." + errSuffix);
}
}
config.rng = rng;
return true;
},
// Converts a given UTF16 character string to the HEX representation.
// Each character of the input string is represented by
// `bytesPerChar` bytes in the output string which defaults to 2.
str2hex: function (str, bytesPerChar) {
var hexChars,
max,
out = "",
neededBytes,
num,
i,
len;
if (typeof str !== "string") {
throw new Error("Input must be a character string.");
}
if (!bytesPerChar) {
bytesPerChar = defaults.bytesPerChar;
}
if (typeof bytesPerChar !== "number" || bytesPerChar < 1 || bytesPerChar > defaults.maxBytesPerChar || bytesPerChar % 1 !== 0) {
throw new Error("Bytes per character must be an integer between 1 and " + defaults.maxBytesPerChar + ", inclusive.");
}
hexChars = 2 * bytesPerChar;
max = Math.pow(16, hexChars) - 1;
for (i = 0, len = str.length; i < len; i++) {
num = str[i].charCodeAt();
if (isNaN(num)) {
throw new Error("Invalid character: " + str[i]);
}
if (num > max) {
neededBytes = Math.ceil(Math.log(num + 1) / Math.log(256));
throw new Error("Invalid character code (" + num + "). Maximum allowable is 256^bytes-1 (" + max + "). To convert this character, use at least " + neededBytes + " bytes.");
}
out = padLeft(num.toString(16), hexChars) + out;
}
return out;
},
// Converts a given HEX number string to a UTF16 character string.
hex2str: function (str, bytesPerChar) {
var hexChars,
out = "",
i,
len;
if (typeof str !== "string") {
throw new Error("Input must be a hexadecimal string.");
}
bytesPerChar = bytesPerChar || defaults.bytesPerChar;
if (typeof bytesPerChar !== "number" || bytesPerChar % 1 !== 0 || bytesPerChar < 1 || bytesPerChar > defaults.maxBytesPerChar) {
throw new Error("Bytes per character must be an integer between 1 and " + defaults.maxBytesPerChar + ", inclusive.");
}
hexChars = 2 * bytesPerChar;
str = padLeft(str, hexChars);
for (i = 0, len = str.length; i < len; i += hexChars) {
out = String.fromCharCode(parseInt(str.slice(i, i + hexChars), 16)) + out;
}
return out;
},
// Generates a random bits-length number string using the PRNG
random: function (bits) {
if (typeof bits !== "number" || bits % 1 !== 0 || bits < 2 || bits > 65536) {
throw new Error("Number of bits must be an Integer between 1 and 65536.");
}
if (config.typeCSPRNG === "browserSJCLRandom" && sjcl.random.isReady(sjclParanoia) < 1) {
throw new Error("SJCL isn't finished seeding the RNG yet. Needs new entropy added or more mouse movement.");
}
return bin2hex(config.rng(bits));
},
// Divides a `secret` number String str expressed in radix `inputRadix` (optional, default 16)
// into `numShares` shares, each expressed in radix `outputRadix` (optional, default to `inputRadix`),
// requiring `threshold` number of shares to reconstruct the secret.
// Optionally, zero-pads the secret to a length that is a multiple of padLength before sharing.
share: function (secret, numShares, threshold, padLength) {
var neededBits,
subShares,
x = new Array(numShares),
y = new Array(numShares),
i,
j,
len;
// Security:
// For additional security, pad in multiples of 128 bits by default.
// A small trade-off in larger share size to help prevent leakage of information
// about small-ish secrets and increase the difficulty of attacking them.
padLength = padLength || 128;
if (typeof secret !== "string") {
throw new Error("Secret must be a string.");
}
if (typeof numShares !== "number" || numShares % 1 !== 0 || numShares < 2) {
throw new Error("Number of shares must be an integer between 2 and 2^bits-1 (" + config.maxShares + "), inclusive.");
}
if (numShares > config.maxShares) {
neededBits = Math.ceil(Math.log(numShares + 1) / Math.LN2);
throw new Error("Number of shares must be an integer between 2 and 2^bits-1 (" + config.maxShares + "), inclusive. To create " + numShares + " shares, use at least " + neededBits + " bits.");
}
if (typeof threshold !== "number" || threshold % 1 !== 0 || threshold < 2) {
throw new Error("Threshold number of shares must be an integer between 2 and 2^bits-1 (" + config.maxShares + "), inclusive.");
}
if (threshold > config.maxShares) {
neededBits = Math.ceil(Math.log(threshold + 1) / Math.LN2);
throw new Error("Threshold number of shares must be an integer between 2 and 2^bits-1 (" + config.maxShares + "), inclusive. To use a threshold of " + threshold + ", use at least " + neededBits + " bits.");
}
if (threshold > numShares) {
throw new Error("Threshold number of shares was " + threshold + " but must be less than or equal to the " + numShares + " shares specified as the total to generate.");
}
if (typeof padLength !== "number" || padLength % 1 !== 0 || padLength < 0 || padLength > 1024) {
throw new Error("Zero-pad length must be an integer between 0 and 1024 inclusive.");
}
secret = "1" + hex2bin(secret); // append a 1 as a marker so that we can preserve the correct number of leading zeros in our secret
secret = splitNumStringToIntArray(secret, padLength);
for (i = 0, len = secret.length; i < len; i++) {
subShares = getShares(secret[i], numShares, threshold);
for (j = 0; j < numShares; j++) {
x[j] = x[j] || subShares[j].x.toString(config.radix);
y[j] = padLeft(subShares[j].y.toString(2)) + (y[j] || "");
}
}
for (i = 0; i < numShares; i++) {
x[i] = constructPublicShareString(config.bits, x[i], bin2hex(y[i]));
}
return x;
},
// Generate a new share with id `id` (a number between 1 and 2^bits-1)
// `id` can be a Number or a String in the default radix (16)
newShare: function (id, shares) {
var share;
if (id && typeof id === "string") {
id = parseInt(id, config.radix);
}
if (id && shares && shares[0]) {
share = this.extractShareComponents(shares[0]);
return constructPublicShareString(share.bits, id, this.combine(shares, id));
}
throw new Error("Invalid 'id' or 'shares' Array argument to newShare().");
},
/* test-code */
// export private functions so they can be unit tested directly.
_reset: reset,
_padLeft: padLeft,
_hex2bin: hex2bin,
_bin2hex: bin2hex,
_hasCryptoGetRandomValues: hasCryptoGetRandomValues,
_hasCryptoRandomBytes: hasCryptoRandomBytes,
_hasSJCL: hasSJCL,
_getRNG: getRNG,
_isSetRNG: isSetRNG,
_splitNumStringToIntArray: splitNumStringToIntArray,
_horner: horner,
_lagrange: lagrange,
_getShares: getShares,
_constructPublicShareString: constructPublicShareString
/* end-test-code */
};
// Always initialize secrets with default settings.
secrets.init();
return secrets;
}));
</script>
<script>$ = function(selector) {
return document.querySelectorAll(selector)[0];
}
</script>
<script>// Coordinates the interaction of elements on the page
(function() {
var DOM = {};
DOM.required = $("#required-parts");
DOM.total = $("#total-parts");
DOM.secret = $("#secret");
DOM.distributesize = $("#distributesize");
DOM.recreatesize = $("#recreatesize");
DOM.error = $("#error-message");
DOM.generated = $("#generated");
DOM.parts = $("#parts");
DOM.combined = $("#combined");
DOM.splitSecret = $("#split-secret")
DOM.splitSecretTab = $("#split-secret-tab")
DOM.combineSecret = $("#combine-secret")
DOM.combineSecretTab = $("#combine-secret-tab")
function init() {
// Events
DOM.required.addEventListener("input", generateParts);
DOM.total.addEventListener("input", generateParts);
DOM.secret.addEventListener("input", generateParts);
DOM.parts.addEventListener("input", combineParts);
DOM.splitSecretTab.addEventListener("click", () => {
clearError()
switchTab(true)
})
DOM.combineSecretTab.addEventListener("click", () => {
clearError()
switchTab(false)
})
}
function switchTab(split) {
DOM.splitSecretTab.classList.toggle("font-semibold", split)
DOM.splitSecretTab.classList.toggle("active-tab", split)
DOM.combineSecretTab.classList.toggle("font-semibold", !split)
DOM.combineSecretTab.classList.toggle("active-tab", !split)
DOM.splitSecret.classList.toggle("hidden", !split)
DOM.combineSecret.classList.toggle("hidden", split)
}
function setError(message) {
DOM.error.textContent = "Error: " + message;
DOM.error.classList.toggle("hidden", false)
}
function clearError() {
DOM.error.textContent = "";
DOM.error.classList.toggle("hidden", true)
}
function generateParts() {
// Clear old generated
DOM.generated.innerHTML = "";
// Get the input values
var secret = DOM.secret.value;
var secretHex = secrets.str2hex(secret);
var total = parseFloat(DOM.total.value);
var required = parseFloat(DOM.required.value);
// validate the input
if (total < 2) {
setError("Total must be at least 2")
return;
}
else if (total > 255) {
setError("Total must be at most 255")
return;
}
else if (required < 2) {
setError("Required must be at least 2")
return;
}
else if (required > 255) {
setError("Required must be at most 255")
return;
}
else if (isNaN(total)) {
setError("Invalid value for total")
return;
}
else if (isNaN(required)) {
setError("Invalid value for required")
return;
}
else if (required > total) {
setError("Required must be less than total")
return;
}
else if (secret.length == 0) {
setError("Secret is blank")
return;
}
else {
clearError()
}
// Generate the parts to share
var minPad = 1024; // see https://github.com/amper5and/secrets.js#note-on-security
var shares = secrets.share(secretHex, total, required, minPad);
// Display the parts
for (var i=0; i<shares.length; i++) {
var share = shares[i];
var li = document.createElement("li");
li.classList.add("px-2", "py-2.5", "odd:bg-[#f4f4f3]", "even:bg-[#e9e8e6]");
li.textContent = share;
DOM.generated.appendChild(li);
}
// Update the plain-language info
DOM.distributesize.textContent = total;
DOM.recreatesize.textContent = required;
}
function combineParts() {
// Clear old text
DOM.combined.textContent = "";
// Get the parts entered by the user
var partsStr = DOM.parts.value;
// Validate and sanitize the input
var parts = partsStr.trim().split(/\s+/);
// Combine the parts
try {
var combinedHex = secrets.combine(parts);
var combined = secrets.hex2str(combinedHex);
}
catch (e) {
DOM.combined.textContent = e.message;
}
// Display the combined parts
DOM.combined.textContent = combined;
}
init();
})();
</script>
</body>
</html>