Last active
September 26, 2020 00:02
-
-
Save davidhq/6dbc6301af8f7d321451e50b0afb1c39 to your computer and use it in GitHub Desktop.
seedprotect.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'); | |
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}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: