Skip to content

Instantly share code, notes, and snippets.

View lord-max's full-sized avatar

lord-max

View GitHub Profile
@lord-max
lord-max / checksum_12_words_min.js
Last active May 1, 2021 01:24
BIP39 checksum word via console: when generating BIP39 seed by hand, you will need this script to fix last 4 bits (12th word) with a correct checksum. Minified version with no comments and no error checks. Full version: https://gist.github.com/lord-max/74190d1a211720671e68d4789227b43f
function checksum_12_words_min(data) {
let binstr = (s,l =8) => s.toString(2).padStart(l,'0') // convert to binary `0011...` string
let tohex = (bytes) => bytes.map( x => x.toString(16).padStart(2,0) ).join('')
let bytes = data.map( x => binstr(x - 1, 11)).join('').match(/.{1,8}/g).map( x => parseInt(x, 2))
bytes.pop(); console.log("Entropy is :",tohex(bytes))
window.crypto.subtle.digest("SHA-256", new Uint8Array(bytes).buffer).then( x => {
let hash = new Uint8Array(x)
let cs = binstr(hash[0]).match(/.{1,4}/g)[0]
let bits = [binstr(bytes[15]),cs].join('')
console.log("Your 12th word index is: " + (1+parseInt(bits.substr(1),2)))
@lord-max
lord-max / checksum_12_words.js
Last active January 24, 2023 21:00
When generating BIP39 seed by hand, you will need this script to fix last 4 bits (12th word) with a correct checksum.
// We expect array of 12 words as human readable indexes (1-2048)
function checksum_12_words(data) {
if (data.length != 12) return console.log("ERROR: Need 12 words numbers as input")
let binstr = (s,l =8) => s.toString(2).padStart(l,'0') // convert to binary `0011...` string
let tohex = (bytes) => bytes.map( x => x.toString(16).padStart(2,0) ).join('')
let bytes = data.map( x => binstr(x - 1, 11)) // convert to 0-index, then to binary `0011...`
.join('').match(/.{1,8}/g) // split 8 bits
.map( x => parseInt(x, 2)) // convert to UInt8