前面的几篇文章我们通过使用ethers.js创建以太坊HD钱包(生成BIP-039 + BIP-044钱包),在根据私钥、助记词找回钱包。
链接地址:https://blog.csdn.net/qq_16137795/article/details/83474645
这篇文章我们讲在Java工程中如何生成钱包的助记词、私钥、地址。
org.bitcoinj
bitcoinj-core
0.14.7
org.web3j
core
3.6.0
1、定义一个path路径常量
/**
* path路径
*/
private final static ImmutableList 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 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、写一个main方法调用 createWallet 方法。
public static void main(String[] args) throws Exception {
//创建钱包
createWallet();
}
4、执行main方法 查看输出的钱包信息
助记词:
[length, shaft, sponsor, ankle, during, bullet, coil, sketch, connect, another, stock, digital]
地址:
0x4c78c36e376eb1d701b415eaffc15c29c2170981
私钥:
0x47ae411da5eb66894aa0dae8ca888128205cc7cb23b38675904fda5545c6b2d5
公钥:
bed6ad054f6bacfa1a042a33bb89b51bdfedd883d24558cc3563ebf0cb25cc274fb4bf299f3684a8eb36f4b6c9b5b8add3b1bd6fc1b1178269995bf935d8becb
5、把私钥 导入到 MetaMask 钱包验证 。恢复的地址和我们生成地址一样。
注:下一章我们讲解在Java中离线转账交易。
学如逆水行舟,不进则退。心似平原跑马,易放难收。全栈工程师是指掌握多种技能,并能利用多种技能独立完成产品的人。 也叫全端工程师(同时具备前端和后台能力),英文Full Stack engineer。【人工智能】【区块链】【系统/网络/运维】【云计算/大数据】【数据库】【移动开发】【后端开发】【游戏开发】【UI设计】【微服务】【爬虫】【Java】【Go】【C++】【PHP】【Python】【Android/IOS】【HTML/CSS】【JavaScript】【Node】。。。
欢迎各位大神萌新一起专研分享各行各业技术!