Created
December 22, 2023 08:30
-
-
Save numtel/02827f7c250594cdfccaaa21cd585bc9 to your computer and use it in GitHub Desktop.
Shamir's secret sharing using node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const crypto = require('crypto'); | |
// All by chatgpt4 except this shim line below | |
global.window = {}; | |
const secrets = require('secrets.js'); | |
// Function to generate RSA key pair | |
function generateKeyPair() { | |
return crypto.generateKeyPairSync('rsa', { | |
modulusLength: 2048, | |
publicKeyEncoding: { type: 'spki', format: 'pem' }, | |
privateKeyEncoding: { type: 'pkcs8', format: 'pem' } | |
}); | |
} | |
// Function to split the private key using Shamir's Secret Sharing | |
function splitPrivateKey(privateKey, totalShares, threshold) { | |
// Convert the private key to a hex string | |
const hexPrivateKey = Buffer.from(privateKey).toString('hex'); | |
// Generate the shares | |
return secrets.share(hexPrivateKey, totalShares, threshold); | |
} | |
// Function to reconstruct the private key from shares | |
function reconstructPrivateKey(shares) { | |
const combinedHex = secrets.combine(shares); | |
return Buffer.from(combinedHex, 'hex').toString(); | |
} | |
// Main function to demonstrate the process | |
function main() { | |
const totalShares = 5; // Total number of shares to split the private key into | |
const threshold = 3; // Minimum number of shares required to reconstruct the key | |
// Generate RSA key pair | |
const { publicKey, privateKey } = generateKeyPair(); | |
// Split the private key into shares | |
const shares = splitPrivateKey(privateKey, totalShares, threshold); | |
// Display the public key and shares | |
console.log('Public Key:', publicKey); | |
shares.forEach((share, index) => console.log(`Share ${index + 1}:`, share)); | |
// Example of reconstructing the private key (using the first 'threshold' shares) | |
const reconstructedPrivateKey = reconstructPrivateKey(shares.slice(0, threshold)); | |
console.log('Reconstructed Private Key:', reconstructedPrivateKey); | |
} | |
main(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment