def FromEntropy(entropy_bytes: bytes) -> str: """ Generate mnemonic from the specified entropy bytes. Args: entropy_bytes (bytes): Entropy bytes (accepted lengths in bits: 128, 160, 192, 224, 256) Returns: str: Generated mnemonic from specified entropy Raises: ValueError: If entropy length is not valid """ # Check entropy length in bits entropy_bit_len = len(entropy_bytes) * 8 if entropy_bit_len not in Bip39Const.ENTROPY_BIT_LEN: raise ValueError("Entropy length in bits (%d) is not valid" % entropy_bit_len) # Compute entropy hash entropy_hash_bytes = CryptoUtils.Sha256(entropy_bytes) # Convert entropy to binary string entropy_bin = ConvUtils.BytesToBinaryStr(entropy_bytes, len(entropy_bytes) * 8) # Convert entropy hash to binary string entropy_hash_bin = ConvUtils.BytesToBinaryStr( entropy_hash_bytes, CryptoUtils.Sha256DigestSize() * 8) # Get checksum binary string checksum_bin = entropy_hash_bin[:len(entropy_bytes) // 4] # Create mnemonic entropy binary string by concatenating entropy and checksum, as specified in BIP39 mnemonic_entropy_bin = entropy_bin + checksum_bin # Create mnemonic reader mnemonic_reader = MnemonicFileReader() # Empty mnemonic mnemonic = [] # Get mnemonic from entropy for i in range(len(mnemonic_entropy_bin) // Bip39Const.WORD_BITS): # Get current word index word_idx = int( mnemonic_entropy_bin[i * Bip39Const.WORD_BITS:(i + 1) * Bip39Const.WORD_BITS], 2) # Get word at given index mnemonic.append(mnemonic_reader.GetWordAtIdx(word_idx)) # Join to string return " ".join(mnemonic)
def __ComputeChecksum(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.__GetEntropyBytes(mnemonic_bin_str) # Convert entropy hash to binary string entropy_hash_bin = ConvUtils.BytesToBinaryStr(CryptoUtils.Sha256(entropy_bytes), CryptoUtils.Sha256DigestSize() * 8) # Compute checksum checksum_bin = entropy_hash_bin[:self.__GetChecksumLen(mnemonic_bin_str)] return checksum_bin