Mnemonic Seed – How to calculate BIP39 checksum bytes correctly?
I’m trying to understand the logic behind generating a valid BIP-39 seed phrase. I’m reading BIP-39 and trying to implement the mnemonic creation section step by step. There is the following Crystal code that works very well for 256-bit seeds, which I found in the answer to the following question: How to generate a valid hash for a bip39 seed phrase?
# First, an initial entropy of ENT bits is generated.
entropy = "87c1b129fbadd7b6e9abc0a9ef7695436d767aece042bec198a97e949fcbe14c"
# => "87c1b129fbadd7b6e9abc0a9ef7695436d767aece042bec198a97e949fcbe14c"
# A checksum is generated by taking the first ENT / 32 bits of its SHA256 hash.
sha2sum = OpenSSL::Digest.new("SHA256").update(entropy.hexbytes).final.hexstring
# => "0dc811788c7e02c32b9c4b3586baf58ca27f74330c92d661042b19faa6c7e9f2"
# the checksum length (CS): 2 (hex) := 8 (bits)
checksum_length_hex = 2
# => 2
checksum = sha2sum(0, checksum_length_hex)
# => "0d"
# This checksum is appended to the end of the initial entropy.
entropy_checksummed = entropy + checksum
# => "87c1b129fbadd7b6e9abc0a9ef7695436d767aece042bec198a97e949fcbe14c0d"
As I said, this works and my code is able to generate the correct index for the words I need, and the resulting syntax matches the syntax provided in the other thread.
But my problem is how do we manage? checksum_length_hex
What about entropy of 160, 192, 224 bits? As I said, my code works on 256 bits. checksum_length_hex
~ Of 2
It also works with lengths of 128 bits. 1
.
But how do you handle the cases in between? Unable to create prefix. 1.2
. I was thinking of taking the checksum prefix with pure bits (e.g. 5 bits for 160 entropy), but I ended up with just gibberish. The following table is taken directly from BIP-39.
# | ENT | CS | ENT+CS | MS |
# +-------+----+--------+------+
# | 128 | 4 | 132 | 12 |
# | 160 | 5 | 165 | 15 |
# | 192 | 6 | 198 | 18 |
# | 224 | 7 | 231 | 21 |
# | 256 | 8 | 264 | 24 |
How do I correctly calculate the BIP-39 checksum bytes of sizes 5, 6, and 7 for entropies 160, 192, and 224?