def Encode(self, entropy_bytes: bytes) -> Mnemonic: """ Encode bytes to mnemonic phrase. Args: entropy_bytes (bytes): Entropy bytes (accepted lengths in bits: 128, 160, 192, 224, 256) Returns: Mnemonic object: Encoded mnemonic Raises: ValueError: If entropy is not valid """ # Check entropy length entropy_byte_len = len(entropy_bytes) if not Bip39EntropyGenerator.IsValidEntropyByteLen(entropy_byte_len): raise ValueError( f"Entropy byte length ({entropy_byte_len}) is not valid") # Convert entropy to binary string entropy_bin_str = BytesUtils.ToBinaryStr(entropy_bytes, entropy_byte_len * 8) # Get entropy hash as binary string entropy_hash_bin_str = BytesUtils.ToBinaryStr( CryptoUtils.Sha256(entropy_bytes), CryptoUtils.Sha256DigestSize() * 8) # Get mnemonic binary string by concatenating entropy and checksum mnemonic_bin_str = entropy_bin_str + entropy_hash_bin_str[:entropy_byte_len // 4] # Get mnemonic from entropy mnemonic = [] for i in range( len(mnemonic_bin_str) // Bip39MnemonicConst.WORD_BIT_LEN): # Get current word index word_bin_str = ( mnemonic_bin_str[i * Bip39MnemonicConst.WORD_BIT_LEN:(i + 1) * Bip39MnemonicConst.WORD_BIT_LEN]) word_idx = IntegerUtils.FromBinaryStr(word_bin_str) # Get word at given index mnemonic.append(self.m_words_list.GetWordAtIdx(word_idx)) return Bip39Mnemonic.FromList(mnemonic)
def __ComputeChecksumBinaryStr(self, mnemonic_bin_str: str) -> str: """ Compute checksum from mnemonic binary string. Args: mnemonic_bin_str (str): Mnemonic binary string Returns: str: Computed checksum binary string """ # Get entropy bytes entropy_bytes = self.__EntropyBytesFromBinaryStr(mnemonic_bin_str) # Convert entropy hash to binary string entropy_hash_bin_str = BytesUtils.ToBinaryStr( CryptoUtils.Sha256(entropy_bytes), CryptoUtils.Sha256DigestSize() * 8) # Return checksum return entropy_hash_bin_str[:self.__GetChecksumLen(mnemonic_bin_str)]