2

How can i generate private key and address using web3j instead of creating keystore json file

  • it is a good question – Nulik Feb 27 '18 at 15:10
9

Below is my approach, verified by importing the result privatekey into MetaMask and get the same address as expected.

private static JSONObject process(String seed){

         JSONObject processJson = new JSONObject();

         try {
            ECKeyPair ecKeyPair = Keys.createEcKeyPair();
            BigInteger privateKeyInDec = ecKeyPair.getPrivateKey();

            String sPrivatekeyInHex = privateKeyInDec.toString(16);

            WalletFile aWallet = Wallet.createLight(seed, ecKeyPair);
            String sAddress = aWallet.getAddress();


            processJson.put("address", "0x" + sAddress);
            processJson.put("privatekey", sPrivatekeyInHex);


        } catch (CipherException e) {
            //
        } catch (InvalidAlgorithmParameterException e) {
            //
        } catch (NoSuchAlgorithmException e) {
            //
        } catch (NoSuchProviderException e) {
            //
        } 

        return processJson;
}


main(){  // unit test 
    String seed = UUID.randomUUID().toString();
    JSONObject result = process(seed); // get a json containing private key and address
}
  • String sPrivatekeyInHex = privateKeyInDec.toString(16); What this line does ? Could you explian ? – Ajit Soman Feb 28 '18 at 5:12
  • 1
    @Ajit Soman getPrivateKey() is returning decimal, usually we need to use hex string private key. – pyang Feb 28 '18 at 5:42
  • I have posted a question . could you provide me some information regarding this: ethereum.stackexchange.com/questions/41194/… – Ajit Soman Feb 28 '18 at 7:54

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.