一、引入依赖
在spring boot 项目中的 pom.xml文件中加入需要的依赖
<dependency><groupId>org.bitcoinj</groupId><artifactId>bitcoinj-core</artifactId><version>0.14.7</version></dependency><!-- 后面讲解签名转账交易 --><dependency><groupId>org.web3j</groupId><artifactId>core</artifactId><version>3.6.0</version></dependency>
二、创建工具类
1、定义常量
/** * path路径 */private final static ImmutableList<ChildNumber> BIP44_ETH_ACCOUNT_ZERO_PATH =ImmutableList.of(new ChildNumber(44, true), new ChildNumber(60, true),ChildNumber.ZERO_HARDENED, ChildNumber.ZERO);
2、创建 createWallet 方法
/** * 创建钱包 * @throws MnemonicException.MnemonicLengthException */private static void createWallet()throws MnemonicException.MnemonicLengthException {SecureRandom secureRandom = new SecureRandom();byte[] entropy = new byte[DeterministicSeed.DEFAULT_SEED_ENTROPY_BITS / 8];secureRandom.engineNextBytes(entropy);//生成12位助记词List<String>str = MnemonicCode.INSTANCE.toMnemonic(entropy);//使用助记词生成钱包种子byte[] seed = MnemonicCode.toSeed(str, "");DeterministicKey masterPrivateKey = HDKeyDerivation.createMasterPrivateKey(seed);DeterministicHierarchy deterministicHierarchy = new DeterministicHierarchy(masterPrivateKey);DeterministicKey deterministicKey = deterministicHierarchy.deriveChild(BIP44_ETH_ACCOUNT_ZERO_PATH, false, true, new ChildNumber(0));byte[] bytes = deterministicKey.getPrivKeyBytes();ECKeyPair keyPair = ECKeyPair.create(bytes);//通过公钥生成钱包地址String address = Keys.getAddress(keyPair.getPublicKey());System.out.println();System.out.println("助记词:");System.out.println(str);System.out.println();System.out.println("地址:");System.out.println("0x"+address);System.out.println();System.out.println("私钥:");System.out.println("0x"+keyPair.getPrivateKey().toString(16));System.out.println();System.out.println("公钥:");System.out.println(keyPair.getPublicKey().toString(16));}
3、调用结果
助记词:[length, shaft, sponsor, ankle, during, bullet, coil, sketch, connect, another, stock, digital]地址:0x4c78c36e376eb1d701b415eaffc15c29c2170981私钥:0x47ae411da5eb66894aa0dae8ca888128205cc7cb23b38675904fda5545c6b2d5公钥:bed6ad054f6bacfa1a042a33bb89b51bdfedd883d24558cc3563ebf0cb25cc274fb4bf299f3684a8eb36f4b6c9b5b8add3b1bd6fc1b1178269995bf935d8becb
4、私钥 导入到 MetaMask 钱包验证 。
可见恢复的地址和我们生成地址一样。