Skip to content

Instantly share code, notes, and snippets.

@numtel
Created December 22, 2023 08:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save numtel/02827f7c250594cdfccaaa21cd585bc9 to your computer and use it in GitHub Desktop.
Save numtel/02827f7c250594cdfccaaa21cd585bc9 to your computer and use it in GitHub Desktop.
Shamir's secret sharing using node.js
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