craig

2 min read - Posted 18 Dec 19

Creating a Web3j Wallet from a Mnemonic Code (Seed Phrase)

Deriving a private key from a mnemonic code or sentence (often called a seed phrase) is a very common way to generate an Ethererum wallet. These seed phrases are usually 12 to 24 words long. As you would expect, web3j provides some tools to allow you to achieve this task in your java code.

Wallet Generation with Default Derivation Path

The default derivation path used by web3j is m/44'/60'/0'/1.

// Web3j supports mnemonic encryption.  No encryption in this example
String password = null;
String mnemonic = "snap escape shadow school illness flip hollow label melt fetch noise install";

// A Credentials object is essentially your wallet, and can be used throughout web3j
// to interact with the Ethereum blockchain with a specific account
Credentials credentials = WalletUtils.loadBip39Credentials(password, mnemonic);

Wallet Generation with Custom Derivation Path

This example creates a private key and credentials with a derivation path of m/44'/60'/0'/0.

String mnemonic = "snap escape shadow school illness flip hollow label melt fetch noise install";

//m/44'/60'/0'/0 derivation path
int[] derivationPath = {44 | Bip32ECKeyPair.HARDENED_BIT, 60 | Bip32ECKeyPair.HARDENED_BIT, 0 | Bip32ECKeyPair.HARDENED_BIT, 0,0};

// Generate a BIP32 master keypair from the mnemonic phrase
Bip32ECKeyPair masterKeypair = Bip32ECKeyPair.generateKeyPair(MnemonicUtils.generateSeed(mnemonic, password));

// Derive the keypair using the derivation path
Bip32ECKeyPair  derivedKeyPair = Bip32ECKeyPair.deriveKeyPair(masterKeypair, derivationPath);

// Load the wallet for the derived keypair
Credentials credentials = Credentials.create(derivedKeyPair);

Thanks to Greg Jeanmart and his excellent article: Manage An Ethereum Account with Java and Web3j.

Created with Sketch.Content is"CC-BY-SA 4.0" licensed
Article On-chain
Article Author

Craig Williams

Software Developer @ Kauri / ConsenSys

19

3

2

0 Comments
Related Articles
Sending an Ether Transfer Transaction from One Account to Another in Web3j

To transfer ether from one account to another, a transaction must be sent to the ethereum network. The easiest way to achieve this within your java application

Manage an Ethereum account with Java and Web3j

Other articles in this series: Connecting to an Ethereum client with Java, Eclipse and Web3j Generate a Java Wrapper from your Smart Contract Interacting with a