以太坊:ETH-根据Web3j生成ETH钱包和解析钱包

 1 创建带json文件的ETH钱包,以及解析钱包:

/**
  * 创建钱包
  * 
  * @param String password 密码
  * @param File  walletFilePath 存放钱包文件夹路径
  * @param Boolean  useFullScrypt 是否轻量级钱包
  */

   String  walletFileName = WalletUtils.generateNewWalletFile(password, new File(walletFilePath), false);


/**
  * 加载钱包文件
  * 
  * @param String password 钱包密码
  * @param  File walleFilePath 钱包文件路径
  */
   Credentials credentials = WalletUtils.loadCredentials(password, walleFilePath);

// 获取钱包地址,私钥,公钥
  String address = credentials.getAddress();
  BigInteger publicKey = credentials.getEcKeyPair().getPublicKey().toString(16);
  BigInteger privateKey = credentials.getEcKeyPair().getPrivateKey().toString(16);






2 创建不带json文件的ETH钱包(可以生成json串),以及解析钱包:

/**
  * 创建钱包(不生成file文件,可以生成json)
  *
  * @param String password 密码
  *            
  */
 public static void createWallet(String password) {
  WalletFile walletFile = null;
  ECKeyPair ecKeyPair = null;
  try {
   ecKeyPair = Keys.createEcKeyPair();
   walletFile = Wallet.createStandard(password, ecKeyPair);
   System.out.println("address = " +"0x"+ walletFile.getAddress());
   ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
   String jsonStr = objectMapper.writeValueAsString(walletFile);
   System.out.println("keystore json file " + jsonStr);
  } catch (Exception exception) {
   exception.printStackTrace();
  }
 }


/**
  * 解密keystore 得到私钥及公钥
  * @param keystore 钱包生成的json字符串
  * @param password 创建钱包时的密码
  */
public static String decryptWallet(String keystore, String password) {
  String privateKey = null;
  String publicKey = null;
  ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
  try {
   WalletFile walletFile = objectMapper.readValue(keystore, WalletFile.class);
   ECKeyPair ecKeyPair = null;
   ecKeyPair = Wallet.decrypt(password, walletFile);
   privateKey = ecKeyPair.getPrivateKey().toString(16);
   System.out.println("privateKey = " + privateKey);
   publicKey = ecKeyPair.getPublicKey().toString(16);
   System.out.println("publicKey = " + publicKey);
  return privateKey;
 }

 注意:

通过ECKeyPair对象获取私钥和公钥,注意下面用私钥进行签名时,私钥要转成这种16进制格式,不能用BigInteger类型,不然会报错。
privateKey = ecKeyPair.getPrivateKey().toString(16);
publicKey = ecKeyPair.getPublicKey().toString(16);

 

你可能感兴趣的:(区块链)