Skip to content

Instantly share code, notes, and snippets.

@davidhq
Last active September 26, 2020 00:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidhq/6dbc6301af8f7d321451e50b0afb1c39 to your computer and use it in GitHub Desktop.
Save davidhq/6dbc6301af8f7d321451e50b0afb1c39 to your computer and use it in GitHub Desktop.
seedprotect.js
const crypto = require('crypto');
function lpad(str, padString, length) {
while (str.length < length) str = padString + str;
return str;
}
// converts string '1100' to integer 12
function binaryToByte(bin) {
return parseInt(bin, 2);
}
// returns string, like: '10011'
function bytesToBinary(bytes) {
return bytes.map(x => lpad(x.toString(2), '0', 8)).join('');
}
function getChunks(password) {
// create pseudo-random 256 bits based on password
const hash = crypto
.createHash('sha256')
.update(password)
.digest();
// get actual bits as string, like: '10011000111...'
const bits = bytesToBinary([].slice.call(hash));
// separate in chunks of 5 bits (= 32 combinations)
return bits.match(/.{1,5}/g);
}
function shuffle(mnemonic, password) {
if (password.trim() == '') {
return mnemonic;
}
const chunks = getChunks(password);
const words = mnemonic.split(' ');
const shuffled = [];
// Fisher–Yates shuffle:
// The algorithm effectively puts all the elements into a hat; it continually determines the next element by randomly drawing an element from the hat until no elements remain.
while (words.length > 0) {
const chunk = chunks.splice(0, 1);
const index = binaryToByte(chunk) % words.length;
shuffled.push(words.splice(index, 1));
}
return shuffled.join(' ');
}
const mnemonic =
'word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12 word13 word14 word15 word16 word17 word18 word19 word20 word21 word22 word23 word24';
const password = 'PASSWORD';
const shuffled = shuffle(mnemonic, password);
console.log(`Seedphrase: ${mnemonic}`);
console.log();
console.log(`Shuffling with password "${password}"...`);
console.log();
console.log(`Shuffled: ${shuffled}`);
@davidhq
Copy link
Author

davidhq commented Apr 8, 2020

Output:

Seedphrase: word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12 word13 word14 word15 word16 word17 word18 word19 word20 word21 word22 word23 word24

Shuffling with password "PASSWORD"...

Shuffled: word2 word17 word22 word6 word3 word11 word8 word19 word18 word10 word9 word4 word13 word23 word1 word14 word7 word15 word16 word12 word21 word24 word5 word20

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment