Files
general-scripts-and-system-…/Web-Tools/Princess_Pi_SSS_Shamirs_Secret_Share_Web_Tools.html
2026-10-26 05:02:19 -06:00

1019 lines
50 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Princess Pi's Shamir's Secret Share Web UI</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Google Fonts for Cassettepunk / Emo Aesthetic -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=VT323&family=Space+Mono:ital,wght@0,400;0,700;1,400&family=Plus+Jakarta+Sans:wght@400;600;700&display=swap" rel="stylesheet">
<script>
tailwind.config = {
theme: {
extend: {
colors: {
tape: {
bg: '#121319',
card: '#1a1c24',
border: '#2a2d3a',
pink: '#ff9ebb',
lavender: '#c6b8f7',
cyan: '#8ae8e8',
teal: '#4fd1c5',
darkText: '#0f1117',
muted: '#94a3b8'
}
},
fontFamily: {
mono: ['"Space Mono"', 'monospace'],
display: ['"VT323"', 'monospace'],
sans: ['"Plus Jakarta Sans"', 'sans-serif']
}
}
}
}
</script>
<style>
/* Retro CRT Scanline & Cassette Texture Effects */
body {
background-color: #121319;
color: #e2e8f0;
background-image: radial-gradient(#262936 1px, transparent 1px);
background-size: 20px 20px;
}
.scanlines {
position: relative;
overflow: hidden;
}
.scanlines::before {
content: " ";
display: block;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
background: linear-gradient(rgba(18, 19, 25, 0) 50%, rgba(0, 0, 0, 0.25) 50%);
background-size: 100% 4px;
z-index: 40;
pointer-events: none;
opacity: 0.6;
}
/* Tape label sticker styling */
.tape-label {
background: #f4efe6;
color: #1a1c24;
box-shadow: 4px 4px 0px #000000;
border: 2px solid #1a1c24;
position: relative;
}
.tape-label::before {
content: '';
position: absolute;
top: 0; left: 0; right: 0; bottom: 0;
border: 1px dashed #d1c7b7;
margin: 3px;
pointer-events: none;
}
/* Neon & Pastel Glows */
.btn-pink {
background-color: #ff9ebb;
color: #121319;
box-shadow: 3px 3px 0px #c6b8f7;
transition: all 0.15s ease-in-out;
}
.btn-pink:hover:not(:disabled) {
transform: translate(-2px, -2px);
box-shadow: 5px 5px 0px #c6b8f7;
background-color: #ffaec5;
}
.btn-pink:active:not(:disabled) {
transform: translate(1px, 1px);
box-shadow: 1px 1px 0px #c6b8f7;
}
.btn-lavender {
background-color: #c6b8f7;
color: #121319;
box-shadow: 3px 3px 0px #8ae8e8;
transition: all 0.15s ease-in-out;
}
.btn-lavender:hover:not(:disabled) {
transform: translate(-2px, -2px);
box-shadow: 5px 5px 0px #8ae8e8;
background-color: #d3c7fa;
}
.btn-lavender:active:not(:disabled) {
transform: translate(1px, 1px);
box-shadow: 1px 1px 0px #8ae8e8;
}
.btn-cyan {
background-color: #8ae8e8;
color: #121319;
box-shadow: 3px 3px 0px #ff9ebb;
transition: all 0.15s ease-in-out;
}
.btn-cyan:hover:not(:disabled) {
transform: translate(-2px, -2px);
box-shadow: 5px 5px 0px #ff9ebb;
background-color: #9bf0f0;
}
.btn-cyan:active:not(:disabled) {
transform: translate(1px, 1px);
box-shadow: 1px 1px 0px #ff9ebb;
}
.btn-dark {
background-color: #2a2d3a;
color: #e2e8f0;
border: 1px solid #3f4457;
box-shadow: 3px 3px 0px #121319;
transition: all 0.15s ease-in-out;
}
.btn-dark:hover:not(:disabled) {
transform: translate(-1px, -1px);
box-shadow: 4px 4px 0px #121319;
background-color: #353949;
color: #ff9ebb;
}
/* Retro Input Focus */
input:focus, textarea:focus {
outline: none;
border-color: #ff9ebb !important;
box-shadow: 0 0 10px rgba(255, 158, 187, 0.3);
}
/* Custom Scrollbar */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: #121319;
}
::-webkit-scrollbar-thumb {
background: #2a2d3a;
border-radius: 4px;
border: 1px solid #ff9ebb;
}
</style>
</head>
<body class="scanlines min-h-screen flex flex-col justify-between font-sans selection:bg-tape-pink selection:text-tape-darkText">
<!-- Top Navigation Header -->
<header class="border-b-2 border-tape-border bg-tape-card bg-opacity-90 backdrop-blur sticky top-0 z-30">
<div class="max-w-6xl mx-auto px-4 py-4 flex flex-col md:flex-row items-center justify-between gap-4">
<!-- Branding / Logo -->
<div class="flex items-center gap-3 cursor-pointer" onclick="switchView('home')">
<div class="w-10 h-10 bg-tape-pink rounded-lg flex items-center justify-center text-tape-darkText font-display text-2xl font-bold border-2 border-black shadow-[2px_2px_0px_#c6b8f7]">
π
</div>
<div>
<h1 class="font-display text-2xl md:text-3xl text-tape-pink tracking-wide leading-none uppercase drop-shadow-[0_2px_4px_rgba(255,158,187,0.2)]">
Princess Pi's
</h1>
<p class="font-mono text-xs text-tape-lavender tracking-wider uppercase">Shamir's Secret Share Web UI</p>
</div>
</div>
<!-- Global Action Controls (Rule 7) -->
<div class="flex flex-wrap items-center gap-2">
<button onclick="resetCurrentForm()" class="btn-dark text-xs font-mono uppercase px-3 py-2 rounded font-bold flex items-center gap-1" title="Clear form fields in current view">
<span>↺</span> Reset Form
</button>
<button onclick="startOver()" class="btn-dark text-xs font-mono uppercase px-3 py-2 rounded font-bold flex items-center gap-1" title="Reload app bypassing cache">
<span>⚡</span> Start Over
</button>
<button onclick="switchView('home')" class="btn-lavender text-xs font-mono uppercase px-3 py-2 rounded font-bold flex items-center gap-1">
<span>⌂</span> Home
</button>
</div>
</div>
</header>
<!-- Main Content Container -->
<main class="max-w-5xl mx-auto px-4 py-8 flex-grow w-full">
<!-- ================= VIEW 1: HOME LANDING (Rule 5) ================= -->
<section id="view-home" class="space-y-8 animate-fade-in">
<!-- Cassette Tape Banner Motif -->
<div class="tape-label p-6 md:p-8 rounded-sm max-w-2xl mx-auto text-center">
<div class="flex justify-between items-center border-b border-gray-400 pb-2 mb-4 font-mono text-xs text-gray-600">
<span>SIDE A: SECRET RECOVERY SYSTEM</span>
<span>90 MIN // HIGH BIAS</span>
</div>
<h2 class="font-display text-4xl md:text-5xl text-gray-900 tracking-wide mb-2 uppercase">
Split & Rebuild Secrets
</h2>
<p class="font-mono text-xs md:text-sm text-gray-700 max-w-md mx-auto leading-relaxed">
Zero-trust client-side cryptographic key splitting powered by polynomial interpolation over GF(256).
</p>
<!-- Cassette Wheels Visual -->
<div class="flex justify-center items-center gap-8 my-6">
<div class="w-12 h-12 rounded-full border-4 border-gray-800 flex items-center justify-center bg-gray-200 animate-spin" style="animation-duration: 12s;">
<div class="w-4 h-4 bg-gray-800 rounded-sm"></div>
</div>
<div class="h-1 bg-gray-800 flex-grow max-w-[120px] rounded"></div>
<div class="w-12 h-12 rounded-full border-4 border-gray-800 flex items-center justify-center bg-gray-200 animate-spin" style="animation-duration: 12s;">
<div class="w-4 h-4 bg-gray-800 rounded-sm"></div>
</div>
</div>
</div>
<!-- Main Navigation Buttons -->
<div class="grid grid-cols-1 md:grid-cols-3 gap-6 max-w-4xl mx-auto pt-4">
<button onclick="switchView('generate')" class="btn-pink p-6 rounded-lg font-mono text-left flex flex-col justify-between h-44 border-2 border-black group">
<div class="text-xs tracking-widest uppercase opacity-80">[ Action 01 ]</div>
<div>
<div class="font-display text-2xl uppercase font-bold group-hover:translate-x-1 transition-transform">
Generate New Shares →
</div>
<p class="text-xs font-sans mt-2 opacity-90 leading-snug">
Split a secret message into X key shares requiring Y to restore.
</p>
</div>
</button>
<button onclick="switchView('decode')" class="btn-lavender p-6 rounded-lg font-mono text-left flex flex-col justify-between h-44 border-2 border-black group">
<div class="text-xs tracking-widest uppercase opacity-80">[ Action 02 ]</div>
<div>
<div class="font-display text-2xl uppercase font-bold group-hover:translate-x-1 transition-transform">
Decode Existing Shares →
</div>
<p class="text-xs font-sans mt-2 opacity-90 leading-snug">
Upload or paste Y shares to reconstruct your original secret.
</p>
</div>
</button>
<button onclick="switchView('docs')" class="btn-cyan p-6 rounded-lg font-mono text-left flex flex-col justify-between h-44 border-2 border-black group">
<div class="text-xs tracking-widest uppercase opacity-80">[ Action 03 ]</div>
<div>
<div class="font-display text-2xl uppercase font-bold group-hover:translate-x-1 transition-transform">
Read More About SSS →
</div>
<p class="text-xs font-sans mt-2 opacity-90 leading-snug">
Learn the mathematics, security guarantees, and user guide.
</p>
</div>
</button>
</div>
</section>
<!-- ================= VIEW 2: GENERATE SHARES (Rule 2) ================= -->
<section id="view-generate" class="hidden space-y-6">
<div class="border-b border-tape-border pb-4 flex flex-col md:flex-row md:items-end justify-between gap-2">
<div>
<span class="font-mono text-xs text-tape-pink uppercase tracking-widest">// MODE: SPLIT_SECRET</span>
<h2 class="font-display text-4xl text-tape-pink uppercase tracking-wide">Generate New Secret Shares</h2>
</div>
<div class="font-mono text-xs text-tape-muted">
Standard GF(256) Byte-Level Scheme
</div>
</div>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<!-- Left Input Controls (2 Cols) -->
<div class="lg:col-span-2 space-y-6 bg-tape-card p-6 rounded-lg border border-tape-border">
<!-- Secret Input Textarea -->
<div>
<div class="flex justify-between items-center mb-2">
<label for="gen-secret" class="font-mono text-xs font-bold text-tape-lavender uppercase tracking-wide">
1. Enter Your Secret Message
</label>
<!-- Live Char Counter & Max Limit (Rule 1) -->
<span id="gen-char-count" class="font-mono text-xs text-tape-cyan bg-tape-bg px-2 py-1 rounded border border-tape-border">
0 / 1024 chars
</span>
</div>
<textarea id="gen-secret" rows="6" oninput="updateCharCounter()" placeholder="Type or paste your sensitive secret text here (passphrases, master keys, private notes)..." class="w-full bg-tape-bg border border-tape-border rounded p-3 text-sm font-mono text-gray-200 placeholder-gray-600 focus:outline-none"></textarea>
</div>
<!-- Threshold & Share Count Parameters -->
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4 pt-2">
<div class="bg-tape-bg p-4 rounded border border-tape-border space-y-2">
<label for="gen-total-x" class="font-mono text-xs font-bold text-tape-cyan uppercase block">
Total Shares To Create (X)
</label>
<input type="number" id="gen-total-x" min="2" max="255" value="5" onchange="validateGenParameters()" class="w-full bg-tape-card border border-tape-border rounded p-2 text-base font-mono font-bold text-tape-pink focus:outline-none">
<p class="text-[11px] text-tape-muted font-mono">Total output files created (2 ≤ X ≤ 255)</p>
</div>
<div class="bg-tape-bg p-4 rounded border border-tape-border space-y-2">
<label for="gen-threshold-y" class="font-mono text-xs font-bold text-tape-pink uppercase block">
Threshold Required (Y)
</label>
<input type="number" id="gen-threshold-y" min="2" max="255" value="3" onchange="validateGenParameters()" class="w-full bg-tape-card border border-tape-border rounded p-2 text-base font-mono font-bold text-tape-pink focus:outline-none">
<p class="text-[11px] text-tape-muted font-mono">Minimum shares needed to decode (2 ≤ Y ≤ X)</p>
</div>
</div>
<!-- Parameter Warning/Info Badge -->
<div id="gen-param-badge" class="font-mono text-xs p-3 rounded bg-tape-bg border border-tape-border text-tape-lavender flex items-center justify-between">
<span>Config: <strong class="text-white" id="badge-scheme-summary">3-of-5 Scheme</strong></span>
<span class="text-tape-muted text-[11px]">Any 2 shares reveal NOTHING.</span>
</div>
<!-- Action Button -->
<button onclick="generateAndDownloadShares()" class="btn-pink w-full py-4 rounded font-mono font-bold text-base uppercase tracking-wider flex items-center justify-center gap-2 border border-black">
<span>💾</span> Generate & Download Shares (.txt)
</button>
</div>
<!-- Right Side Information Tape -->
<div class="space-y-4">
<div class="tape-label p-5 rounded">
<h3 class="font-display text-xl text-gray-900 border-b border-gray-400 pb-1 mb-3 uppercase">
Share Settings Rules
</h3>
<ul class="text-xs font-mono text-gray-800 space-y-2 list-disc pl-4">
<li><strong>X (Total Shares):</strong> How many individual text files will be downloaded.</li>
<li><strong>Y (Threshold):</strong> Minimum shares required to reconstruct the original message.</li>
<li><strong>Security:</strong> Possessing Y-1 or fewer shares mathematically provides <em>zero</em> knowledge of the secret.</li>
<li><strong>Limit:</strong> Up to 1024 UTF-8 characters per secret byte array chunk.</li>
</ul>
</div>
<!-- Download Activity Log -->
<div class="bg-tape-card border border-tape-border rounded p-4 font-mono text-xs space-y-2">
<div class="text-tape-lavender font-bold uppercase border-b border-tape-border pb-1">System Status</div>
<div id="gen-status-log" class="text-tape-muted h-32 overflow-y-auto space-y-1">
> Ready to split secret into shares.
</div>
</div>
</div>
</div>
</section>
<!-- ================= VIEW 3: DECODE SHARES (Rule 4) ================= -->
<section id="view-decode" class="hidden space-y-6">
<div class="border-b border-tape-border pb-4 flex flex-col md:flex-row md:items-end justify-between gap-2">
<div>
<span class="font-mono text-xs text-tape-lavender uppercase tracking-widest">// MODE: RECOMBINE_SHARES</span>
<h2 class="font-display text-4xl text-tape-lavender uppercase tracking-wide">Decode Existing Shares</h2>
</div>
<div class="font-mono text-xs text-tape-muted">
Lagrange Interpolation over GF(256)
</div>
</div>
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<!-- Method A: File Upload -->
<div class="bg-tape-card p-6 rounded-lg border border-tape-border flex flex-col justify-between space-y-4">
<div>
<h3 class="font-mono text-xs font-bold text-tape-cyan uppercase tracking-wide mb-2">
Option A: Drag & Drop / Upload .TXT Share Files
</h3>
<div id="drop-zone" class="border-2 border-dashed border-tape-border hover:border-tape-cyan transition-colors rounded-lg p-6 text-center bg-tape-bg cursor-pointer space-y-3" onclick="document.getElementById('file-input').click()">
<div class="text-3xl">📁</div>
<div class="font-mono text-xs text-tape-lavender">
Click to select or drop <span class="text-tape-cyan font-bold">.txt share files</span> here
</div>
<div class="font-mono text-[10px] text-tape-muted">
Upload multiple files generated by this UI at once
</div>
<input type="file" id="file-input" multiple accept=".txt" class="hidden" onchange="handleFileUpload(event)">
</div>
</div>
<!-- Uploaded Files List -->
<div class="bg-tape-bg p-3 rounded border border-tape-border">
<div class="flex justify-between items-center font-mono text-xs text-tape-muted mb-2">
<span>Loaded File Shares:</span>
<span id="file-count-tag" class="text-tape-pink font-bold">0 files</span>
</div>
<div id="file-list-display" class="font-mono text-xs text-tape-lavender max-h-24 overflow-y-auto space-y-1">
<span class="text-tape-muted italic">No files loaded yet...</span>
</div>
</div>
</div>
<!-- Method B: Direct Paste -->
<div class="bg-tape-card p-6 rounded-lg border border-tape-border flex flex-col justify-between space-y-4">
<div>
<h3 class="font-mono text-xs font-bold text-tape-pink uppercase tracking-wide mb-2">
Option B: Paste Share Payloads (One per line or blocks)
</h3>
<textarea id="decode-text-input" rows="7" placeholder="Paste share blocks or raw payload strings here...
Example format:
SSS1-0103-8A4F...
SSS1-0203-99B2..." class="w-full bg-tape-bg border border-tape-border rounded p-3 text-xs font-mono text-gray-200 placeholder-gray-600 focus:outline-none" oninput="parsePastedShares()"></textarea>
</div>
<div class="flex justify-end">
<button onclick="clearDecodeInputs()" class="text-xs font-mono text-tape-muted hover:text-tape-pink underline">
Clear Input Data
</button>
</div>
</div>
</div>
<!-- Decode Action & Detected Metadata -->
<div class="bg-tape-card p-6 rounded-lg border border-tape-border space-y-4">
<div class="flex flex-col sm:flex-row items-center justify-between gap-4 bg-tape-bg p-4 rounded border border-tape-border font-mono text-xs">
<div class="space-y-1">
<div>Detected Shares: <span id="detected-count" class="text-tape-cyan font-bold">0</span></div>
<div>Estimated Scheme: <span id="detected-scheme" class="text-tape-lavender font-bold">Unknown (Need data)</span></div>
</div>
<button onclick="decodeSecretAction()" class="btn-lavender w-full sm:w-auto px-8 py-3 rounded font-mono font-bold text-sm uppercase tracking-wider border border-black">
🔓 Reconstruct Secret
</button>
</div>
<!-- Decoded Output Display -->
<div id="decode-result-box" class="hidden space-y-2">
<label class="font-mono text-xs font-bold text-tape-cyan uppercase tracking-wide block">
Reconstructed Secret Result:
</label>
<div class="relative">
<textarea id="decoded-output" readonly rows="5" class="w-full bg-tape-bg border-2 border-tape-cyan rounded p-4 text-sm font-mono text-tape-cyan focus:outline-none"></textarea>
<button onclick="copyDecodedSecret()" class="absolute top-3 right-3 btn-dark text-xs font-mono px-3 py-1 rounded">
Copy Secret
</button>
</div>
</div>
<!-- Error Alert Box -->
<div id="decode-error-box" class="hidden p-4 rounded bg-red-950 border border-red-500 font-mono text-xs text-red-200">
<div class="font-bold uppercase flex items-center gap-2 mb-1">
<span>⚠ Decoding Error</span>
</div>
<div id="decode-error-msg">Insufficient valid shares supplied.</div>
</div>
</div>
</section>
<!-- ================= VIEW 4: READ MORE / DOCUMENTATION (Rule 6) ================= -->
<section id="view-docs" class="hidden space-y-8">
<!-- App Usage Guide (Top Section per Rule 6) -->
<div class="tape-label p-6 md:p-8 rounded space-y-4">
<div class="flex justify-between items-center border-b border-gray-400 pb-2 font-mono text-xs text-gray-700">
<span>DOCUMENTATION & USER MANUAL</span>
<span>REF: SSS-STATIC-LOCAL</span>
</div>
<h2 class="font-display text-3xl md:text-4xl text-gray-900 uppercase font-bold">
How to Use SSS-Shamirs-Secret-Sharing-Static-Local.html
</h2>
<div class="font-sans text-xs md:text-sm text-gray-800 space-y-3 leading-relaxed">
<p>
This standalone tool operates <strong>100% offline and locally inside your browser</strong>. No secret keys, passphrases, or calculated shares are ever transmitted over a network. You can save this HTML file to an air-gapped flash drive and run it on any device with a web browser.
</p>
<p>
<strong>Generating Shares:</strong> Click on <em>Generate New Shares</em>, type your sensitive secret into the message area, and select your target thresholds <strong>(X total shares, Y required)</strong>. Clicking <em>Generate & Download Shares</em> will automatically output X individual formatted text files (e.g. <code>2026-10-25-Shamirs-Secret-Shares-1-of-5.txt</code>). Distribute these files to different physical locations, team members, or safe deposit boxes.
</p>
<p>
<strong>Reconstructing the Secret:</strong> When emergency recovery is needed, collect at least <strong>Y</strong> of the downloaded text files. Navigate to <em>Decode Existing Shares</em>, upload the text files directly or paste their contents into the text box, and click <em>Reconstruct Secret</em>.
</p>
</div>
</div>
<!-- Layman Accessible Technical Explanation (Rule 6) -->
<div class="bg-tape-card p-6 md:p-8 rounded-lg border border-tape-border space-y-6">
<div class="border-b border-tape-border pb-3">
<span class="font-mono text-xs text-tape-cyan uppercase tracking-widest">// CRYPTOGRAPHIC THEORY</span>
<h3 class="font-display text-3xl text-tape-cyan uppercase">Understanding Shamir's Secret Sharing</h3>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6 font-sans text-xs md:text-sm text-tape-muted leading-relaxed">
<div class="space-y-4">
<h4 class="font-mono text-sm text-tape-pink font-bold uppercase">1. The Geometric Intuition (2D Polynomials)</h4>
<p>
Imagine basic high school algebra: How many points are needed to define a straight line? The answer is <strong>2 points</strong>. If you are given only 1 point, an infinite number of different lines could pass through it.
</p>
<p>
Similarly, it takes <strong>3 points</strong> to uniquely define a parabola (a polynomial of degree 2, $f(x) = ax^2 + bx + c$). In general, a polynomial of degree $k - 1$ requires exactly $k$ points to be uniquely reconstructed.
</p>
<p>
Shamir's Secret Sharing utilizes this principle: Your secret message is hidden as the constant term (the y-intercept, where $x=0$) of a randomly generated polynomial. Each share distributed to a holder is simply one coordinate $(x, y)$ along that hidden mathematical curve.
</p>
</div>
<div class="space-y-4">
<h4 class="font-mono text-sm text-tape-lavender font-bold uppercase">2. Perfect Information-Theoretic Security</h4>
<p>
Why can't someone guess the secret if they have $Y-1$ shares? Because until you reach the threshold $Y$, the remaining unknown coefficients of the polynomial can take any valid value with equal probability.
</p>
<p>
Having $Y-1$ shares leaves every possible secret message equally plausible. This provides <em>information-theoretic security</em>: even an adversary with infinite computing power cannot extract a single bit of information about your secret without reaching the threshold $Y$.
</p>
</div>
</div>
<div class="bg-tape-bg p-5 rounded border border-tape-border font-sans text-xs md:text-sm text-tape-muted space-y-3">
<h4 class="font-mono text-sm text-tape-cyan font-bold uppercase">3. Byte-Level Galois Field Mathematics GF(256)</h4>
<p>
In standard real-number arithmetic, coordinate calculations generate massive floating-point numbers and fractions that cause precision loss and leak information through number size.
</p>
<p>
This tool performs polynomial calculations over <strong>Galois Field GF($2^{8}$) / GF(256)</strong> using the irreducible primitive polynomial $x^8 + x^4 + x^3 + x + 1$ (0x11B). In GF(256), addition is equivalent to bitwise XOR, and multiplication/division are performed via logarithmic lookup tables. Each byte of your secret (from 0 to 255) is split independently across the exact same degree polynomial, allowing arbitrary UTF-8 text and binary data to be shared with absolute mathematical precision.
</p>
</div>
</div>
</section>
</main>
<!-- Footer -->
<footer class="border-t border-tape-border bg-tape-card py-4 font-mono text-xs text-center text-tape-muted">
<div class="max-w-5xl mx-auto px-4 flex flex-col sm:flex-row justify-between items-center gap-2">
<div>Princess Pi's Cryptographic Suite • GF(256) Local SSS Engine</div>
<div class="text-tape-pink">100% Client-Side • Zero Network Dependencies</div>
</div>
</footer>
<!-- JavaScript SSS Engine & UI Controller -->
<script>
/* =========================================================================
GALOIS FIELD GF(256) CRYPTOGRAPHIC IMPLEMENTATION
Rijndael's finite field primitive polynomial 0x11B (283)
========================================================================= */
const GF256 = (function() {
const exp = new Uint8Array(512);
const log = new Uint8Array(256);
// Initialize exp & log tables for fast multiplication/division
let x = 1;
for (let i = 0; i < 255; i++) {
exp[i] = x;
exp[i + 255] = x;
log[x] = i;
x = x ^ (x << 1);
if (x & 0x100) {
x ^= 0x11B; // Primitive polynomial
}
}
log[0] = 0; // Log(0) undefined, default zero guard
return {
add: (a, b) => a ^ b,
sub: (a, b) => a ^ b,
mul: (a, b) => {
if (a === 0 || b === 0) return 0;
return exp[log[a] + log[b]];
},
div: (a, b) => {
if (b === 0) throw new Error("GF(256) Division by zero");
if (a === 0) return 0;
return exp[(log[a] - log[b] + 255) % 255];
}
};
})();
// Maximum safe secret length in characters for local batch processing
const MAX_SECRET_CHAR_LIMIT = 1024;
/* Evaluate polynomial at x using Horner's method or direct sum */
function evalPolyGF256(poly, x) {
let result = 0;
for (let i = poly.length - 1; i >= 0; i--) {
result = GF256.add(GF256.mul(result, x), poly[i]);
}
return result;
}
/* Generate SSS Shares for a byte array */
function splitSecretBytes(secretBytes, totalSharesX, thresholdY) {
const shares = [];
for (let i = 1; i <= totalSharesX; i++) {
shares.push({ x: i, bytes: new Uint8Array(secretBytes.length) });
}
// For each byte in the secret, construct a random polynomial of degree thresholdY - 1
for (let b = 0; b < secretBytes.length; b++) {
const poly = new Uint8Array(thresholdY);
poly[0] = secretBytes[b]; // Secret is constant term f(0)
// Fill remaining polynomial coefficients with cryptographic random bytes
const randomCoeffs = new Uint8Array(thresholdY - 1);
window.crypto.getRandomValues(randomCoeffs);
for (let c = 1; c < thresholdY; c++) {
poly[c] = randomCoeffs[c - 1];
}
// Evaluate polynomial for each share x = 1..X
for (let i = 0; i < totalSharesX; i++) {
const xVal = shares[i].x;
shares[i].bytes[b] = evalPolyGF256(poly, xVal);
}
}
return shares;
}
/* Lagrange Interpolation over GF(256) to restore secret f(0) */
function reconstructSecretBytes(shares) {
if (shares.length === 0) throw new Error("No shares provided.");
const secretLen = shares[0].bytes.length;
const secret = new Uint8Array(secretLen);
for (let b = 0; b < secretLen; b++) {
let secretByte = 0;
for (let i = 0; i < shares.length; i++) {
const xi = shares[i].x;
const yi = shares[i].bytes[b];
let li = 1; // Lagrange basis polynomial L_i(0)
for (let j = 0; j < shares.length; j++) {
if (i === j) continue;
const xj = shares[j].x;
// Li(0) = product( (0 - xj) / (xi - xj) ) = product( xj / (xi ^ xj) )
const num = xj;
const den = GF256.sub(xi, xj);
const term = GF256.div(num, den);
li = GF256.mul(li, term);
}
const termValue = GF256.mul(yi, li);
secretByte = GF256.add(secretByte, termValue);
}
secret[b] = secretByte;
}
return secret;
}
/* =========================================================================
HEX & BASE64 ENCODING HELPERS FOR PAYLOAD STABILITY
========================================================================= */
function bytesToHex(uint8) {
return Array.from(uint8).map(b => b.toString(16).padStart(2, '0')).join('');
}
function hexToBytes(hex) {
const bytes = new Uint8Array(hex.length / 2);
for (let i = 0; i < bytes.length; i++) {
bytes[i] = parseInt(hex.substr(i * 2, 2), 16);
}
return bytes;
}
/* Calculate simple 4-byte checksum hash to verify shares belong together */
function calcSchemeHash(secretBytes) {
let hash = 0x811c9dc5;
for (let i = 0; i < secretBytes.length; i++) {
hash ^= secretBytes[i];
hash = Math.imul(hash, 0x01000193);
}
return (hash >>> 0).toString(16).padStart(8, '0').toUpperCase();
}
/* =========================================================================
APPLICATION UI NAVIGATION & EVENT HANDLERS
========================================================================= */
let loadedFileShares = [];
function switchView(viewName) {
document.getElementById('view-home').classList.add('hidden');
document.getElementById('view-generate').classList.add('hidden');
document.getElementById('view-decode').classList.add('hidden');
document.getElementById('view-docs').classList.add('hidden');
const target = document.getElementById(`view-${viewName}`);
if (target) {
target.classList.remove('hidden');
}
window.scrollTo({ top: 0, behavior: 'smooth' });
}
/* Rule 7: Control Buttons implementation */
function resetCurrentForm() {
// Clear Generator
document.getElementById('gen-secret').value = '';
document.getElementById('gen-total-x').value = '5';
document.getElementById('gen-threshold-y').value = '3';
updateCharCounter();
validateGenParameters();
document.getElementById('gen-status-log').innerHTML = '> Form reset completed.';
// Clear Decoder
clearDecodeInputs();
}
function startOver() {
// Force reload page bypassing cache if possible
window.location.reload(true);
}
/* Rule 1: Character counter & max limit handling */
function updateCharCounter() {
const textarea = document.getElementById('gen-secret');
let text = textarea.value;
if (text.length > MAX_SECRET_CHAR_LIMIT) {
textarea.value = text.substring(0, MAX_SECRET_CHAR_LIMIT);
text = textarea.value;
}
const counter = document.getElementById('gen-char-count');
counter.innerText = `${text.length} / ${MAX_SECRET_CHAR_LIMIT} chars`;
if (text.length >= MAX_SECRET_CHAR_LIMIT) {
counter.classList.remove('text-tape-cyan');
counter.classList.add('text-tape-pink', 'font-bold');
} else {
counter.classList.remove('text-tape-pink', 'font-bold');
counter.classList.add('text-tape-cyan');
}
}
function validateGenParameters() {
let x = parseInt(document.getElementById('gen-total-x').value, 10) || 2;
let y = parseInt(document.getElementById('gen-threshold-y').value, 10) || 2;
if (x < 2) x = 2;
if (x > 255) x = 255;
if (y < 2) y = 2;
if (y > x) y = x; // Threshold Y cannot exceed total shares X
document.getElementById('gen-total-x').value = x;
document.getElementById('gen-threshold-y').value = y;
document.getElementById('badge-scheme-summary').innerText = `${y}-of-${x} Scheme`;
}
/* =========================================================================
ACTION 1: GENERATE & DOWNLOAD SHARES (Rule 3)
========================================================================= */
function generateAndDownloadShares() {
const secretText = document.getElementById('gen-secret').value;
const x = parseInt(document.getElementById('gen-total-x').value, 10);
const y = parseInt(document.getElementById('gen-threshold-y').value, 10);
const logBox = document.getElementById('gen-status-log');
if (!secretText || secretText.trim() === '') {
logBox.innerHTML += `<div class="text-tape-pink">> ERROR: Secret message cannot be empty!</div>`;
return;
}
const encoder = new TextEncoder();
const secretBytes = encoder.encode(secretText);
const schemeHash = calcSchemeHash(secretBytes);
logBox.innerHTML += `<div>> Encoding secret (${secretBytes.length} bytes)...</div>`;
logBox.innerHTML += `<div>> Computing ${y}-of-${x} polynomial shares over GF(256)...</div>`;
const rawShares = splitSecretBytes(secretBytes, x, y);
// Today's date in YYYY-MM-DD format
const today = new Date();
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, '0');
const day = String(today.getDate()).padStart(2, '0');
const dateStr = `${year}-${month}-${day}`;
// Trigger downloads for each share file
rawShares.forEach((share, index) => {
const orderNum = index + 1;
const hexPayload = bytesToHex(share.bytes);
// Standard share format string: SSS1-[xHex 2 char][yHex 2 char]-[hash 8 char]-[hex payload]
const shareString = `SSS1-${orderNum.toString(16).padStart(2, '0')}${y.toString(16).padStart(2, '0')}-${schemeHash}-${hexPayload}`;
// Structure file contents per Rule 3 requirements
const fileContent =
`================================================================================
PRINCESS PI'S SHAMIR'S SECRET SHARE KEY TAPE
================================================================================
DATE CREATED : ${dateStr}
SHARE INDEX : ${orderNum} of ${x}
THRESHOLD : ${y} shares required to decode secret
SCHEME HASH : ${schemeHash}
================================================================================
RAW SHARE PAYLOAD:
--------------------------------------------------------------------------------
${shareString}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
CONCEPT OVERVIEW (SHAMIR'S SECRET SHARING):
--------------------------------------------------------------------------------
Shamir's Secret Sharing is an algorithm created by Adi Shamir. It splits a secret
into X unique parts (shares) such that any Y of them can reconstruct the original
secret, but possessing fewer than Y shares reveals mathematically zero information
about the secret.
This system relies on polynomial interpolation over Galois Field GF(256). The secret
is embedded as the constant y-intercept f(0) of a random polynomial of degree (Y-1).
Each share represents a unique coordinate point along this polynomial curve.
--------------------------------------------------------------------------------
INSTRUCTIONS TO DECODE THIS SECRET:
--------------------------------------------------------------------------------
1. Collect at least ${y} individual share files from this ${y}-of-${x} key set.
2. Open the static web application file:
"SSS-Shamirs-Secret-Sharing-Static-Local.html" in any modern web browser.
3. Click on the "Decode Existing Shares" button on the main menu.
4. Drag and drop these .txt files directly into the file upload zone, or copy
the RAW SHARE PAYLOAD string above and paste it into the input box.
5. Click "Reconstruct Secret" to reveal the original message.
================================================================================
`;
const fileName = `${dateStr}-Shamirs-Secret-Shares-${orderNum}-of-${x}.txt`;
downloadTxtFile(fileName, fileContent);
});
logBox.innerHTML += `<div class="text-tape-cyan">> SUCCESS: Downloaded ${x} share text files!</div>`;
logBox.scrollTop = logBox.scrollHeight;
}
function downloadTxtFile(filename, text) {
const element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
/* =========================================================================
ACTION 2: DECODE SHARES (Rule 4)
========================================================================= */
function handleFileUpload(event) {
const files = event.target.files;
if (!files || files.length === 0) return;
Array.from(files).forEach(file => {
const reader = new FileReader();
reader.onload = function(e) {
const content = e.target.result;
loadedFileShares.push({ name: file.name, content: content });
updateFileListDisplay();
parseAndValidateAllInputs();
};
reader.readAsText(file);
});
}
function updateFileListDisplay() {
const display = document.getElementById('file-list-display');
const tag = document.getElementById('file-count-tag');
tag.innerText = `${loadedFileShares.length} files`;
if (loadedFileShares.length === 0) {
display.innerHTML = `<span class="text-tape-muted italic">No files loaded yet...</span>`;
return;
}
display.innerHTML = loadedFileShares.map(f => `
<div class="flex justify-between items-center bg-tape-card px-2 py-1 rounded border border-tape-border">
<span class="truncate max-w-[200px]">${f.name}</span>
<span class="text-tape-cyan text-[10px]">Loaded</span>
</div>
`).join('');
}
function parsePastedShares() {
parseAndValidateAllInputs();
}
function extractShareStrings(rawText) {
const shares = [];
// Regex to find SSS1 payloads: SSS1-[xHex(2)][yHex(2)]-[Hash(8)]-[PayloadHex]
const regex = /SSS1-([0-9a-fA-F]{4})-([0-9a-fA-F]{8})-([0-9a-fA-F]+)/g;
let match;
while ((match = regex.exec(rawText)) !== null) {
const params = match[1];
const xVal = parseInt(params.substr(0, 2), 16);
const yVal = parseInt(params.substr(2, 2), 16);
const schemeHash = match[2].toUpperCase();
const hexPayload = match[3];
shares.push({
x: xVal,
y: yVal,
hash: schemeHash,
bytes: hexToBytes(hexPayload)
});
}
return shares;
}
function parseAndValidateAllInputs() {
let combinedText = document.getElementById('decode-text-input').value || '';
// Append contents from uploaded files
loadedFileShares.forEach(f => {
combinedText += '\n' + f.content;
});
const parsedShares = extractShareStrings(combinedText);
// Deduplicate shares by x value
const uniqueSharesMap = new Map();
parsedShares.forEach(s => uniqueSharesMap.set(s.x, s));
const shares = Array.from(uniqueSharesMap.values());
document.getElementById('detected-count').innerText = shares.length;
if (shares.length > 0) {
const reqY = shares[0].y;
const hash = shares[0].hash;
document.getElementById('detected-scheme').innerText = `${reqY} Required (Hash: ${hash})`;
} else {
document.getElementById('detected-scheme').innerText = 'Unknown (Need data)';
}
return shares;
}
function decodeSecretAction() {
const shares = parseAndValidateAllInputs();
const errorBox = document.getElementById('decode-error-box');
const resultBox = document.getElementById('decode-result-box');
const output = document.getElementById('decoded-output');
errorBox.classList.add('hidden');
resultBox.classList.add('hidden');
if (shares.length === 0) {
showDecodeError("No valid SSS share payloads found in inputs. Upload files or paste share strings.");
return;
}
const requiredY = shares[0].y;
const targetHash = shares[0].hash;
// Check if all shares belong to the same scheme
const mismatched = shares.some(s => s.hash !== targetHash);
if (mismatched) {
showDecodeError("Corrupted share set: Detected shares from different secrets or schemes!");
return;
}
if (shares.length < requiredY) {
showDecodeError(`Insufficient shares! Provided ${shares.length} valid share(s), but this secret scheme requires at least ${requiredY} shares to reconstruct.`);
return;
}
try {
const secretBytes = reconstructSecretBytes(shares);
const decoder = new TextDecoder('utf-8', { fatal: true });
const decodedText = decoder.decode(secretBytes);
output.value = decodedText;
resultBox.classList.remove('hidden');
} catch (err) {
showDecodeError("Decoding failed! The shares may be corrupted or corrupted byte data was supplied.");
}
}
function showDecodeError(msg) {
const errorBox = document.getElementById('decode-error-box');
document.getElementById('decode-error-msg').innerText = msg;
errorBox.classList.remove('hidden');
}
function clearDecodeInputs() {
loadedFileShares = [];
document.getElementById('decode-text-input').value = '';
document.getElementById('file-input').value = '';
document.getElementById('decode-result-box').classList.add('hidden');
document.getElementById('decode-error-box').classList.add('hidden');
updateFileListDisplay();
parseAndValidateAllInputs();
}
function copyDecodedSecret() {
const copyText = document.getElementById("decoded-output");
copyText.select();
copyText.setSelectionRange(0, 99999);
document.execCommand("copy");
}
/* Drag & Drop event bindings */
const dropZone = document.getElementById('drop-zone');
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
dropZone.addEventListener(eventName, preventDefaults, false);
});
function preventDefaults(e) {
e.preventDefault();
e.stopPropagation();
}
dropZone.addEventListener('drop', (e) => {
const dt = e.dataTransfer;
const files = dt.files;
handleFileUpload({ target: { files: files } });
});
// Initialize state on load
window.onload = function() {
updateCharCounter();
validateGenParameters();
};
</script>
</body>
</html>