derivePrivateKeyFromMnemonic method Null safety
Returns a raw hex-encoded string for a given mnemonic
Implementation
String derivePrivateKeyFromMnemonic(String mnemonic, String derivationPath,
[int change = 0, int addressIndex = 0]) {
assert(derivationPath.substring(0, 2) == 'm/');
final List<String> derivationPathSplit =
derivationPath.substring(2).split('/');
final List<BigInt> derivationPathLst = [];
// ignore: avoid_function_literals_in_foreach_calls
derivationPathSplit.forEach((String indivComponent) {
if (indivComponent.contains('\'')) {
derivationPathLst.add(BigInt.from(
2147483648 + int.parse(indivComponent.replaceAll('\'', ''))));
} else {
derivationPathLst.add(BigInt.from(int.parse(indivComponent)));
}
});
final Uint8List seed = bip39.mnemonicToSeed(mnemonic);
final Uint8List hash = (HMac(SHA512Digest(), 128)
..init(KeyParameter(utf8.encoder.convert('Bitcoin seed'))))
.process(seed);
Uint8List key = hash.sublist(0, 32);
Uint8List chain = hash.sublist(32);
// ignore: avoid_function_literals_in_foreach_calls
derivationPathLst.forEach((BigInt path) {
final List<Uint8List> keyAndChain =
_deriveBip32ChildKey(key, chain, path);
key = keyAndChain[0];
chain = keyAndChain[1];
});
return hex.encode(key);
}