Ethereum Wallet Generation In An Android Application

Posted By : Keshav Gupta | 16-Feb-2018

Step1: integrate the following dependency in app/build.gradle

 compile ('org.web3j:core-android:2.2.1')

The web3j core is there core library used for downloading ethereum blockchain data from its server.It is generally used for ethereum.

Step2: We will be designing an android UI sample screen which will be having an edit text and a button.In EditText it will ask for the user to enter a password for the wallet. Then on click event of the button, we will start a process of sending the password.Following is layout.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/content"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical">
    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:hint="@string/textview_password"
        android:padding="10dp"/>
    <Button
        android:id="@+id/generate_wallet_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/textview_generate_wallet"/>
</LinearLayout>

Step3: We will be creating a FileOutputStream path to save the created wallet file in storage and will also require read-write storage permission

Step4: For android user Api>26 you need to seek for runtime permission for doing that above step.

Step5: Then there is a class named as WalletUtils. in  web3jcore.In that class, there is a method generateWalletNewFile(password, path) that will accept password param and path for wallet file. that will create wallet file.

Step6: There are one more class Credentials in web3jcore which will load all credentials of the file using WalletUtils.loadCredentials(password,path)  method.Following are one class and interface that will be used to generate wallet file

public class EthereumGenerationPresenter implements EthereumGenerationContract.Presenter {

    private final EthereumGenerationContract.View mWalletGenerationView;

    private String mPassword;

    public EthereumGenerationPresenter(EthereumGenerationContract.View walletGenerationView, String password) {
        mWalletGenerationView = walletGenerationView;
        mPassword = password;
    }

    @Override
    public void generateWallet(final String password) {
        String fileName;
        try {
            File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            if (!path.exists()) {
                path.mkdir();
            }
            fileName = WalletUtils.generateLightNewWalletFile(password, new File(String.valueOf(path)));
            Log.e("TAG", "generateWallet: " + path+ "/" + fileName);
            Credentials credentials =
                    WalletUtils.loadCredentials(
                            password,
                            path + "/" + fileName);
            mWalletGenerationView.showGeneratedWallet(credentials.getAddress());
            Log.e("TAG", "generateWallet: " + credentials.getAddress() + " " + credentials.getEcKeyPair().getPublicKey());
        } catch (NoSuchAlgorithmException
                | NoSuchProviderException
                | InvalidAlgorithmParameterException
                | IOException
                | CipherException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void start() {
        generateWallet(mPassword);
    }
}
public interface EthereumGenerationContract {

    interface View extends BaseView<Presenter> {

        void showGeneratedWallet(String walletAddress);
    }

    interface Presenter extends BasePresenter {

        void generateWallet(String password);
    }
}

 

public interface BasePresenter {

    void start();
}

 

public interface BaseView<T> {

    void setPresenter(T presenter);
}

Step7: Now Credentials class will be holding wallet address of ethereum and much more information of that file.

Step8: Now address can be obtained using

  credentials.getAddress()->

 Public key

 credentials.getPublicKey()

PrivateKey

credentials.getEcKeyPair()

Step9: Wallet generation activity class be like:

public class WalletGenerationActivity extends AppCompatActivity implements EthereumGenerationContract.View {

    private static final int REQUEST_PERMISSION_WRITE_STORAGE = 0;

    private EthereumGenerationContract.Presenter mWalletPresenter;

    private Button mGenerateWalletButton;

    private String mWalletAddress;

    private EditText mPassword;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_generation);

        mGenerateWalletButton = (Button) findViewById(R.id.generate_wallet_button);
        mPassword = (EditText) findViewById(R.id.password);

        mGenerateWalletButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int permissionCheck = ContextCompat.checkSelfPermission(WalletGenerationActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE);
                if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(
                            WalletGenerationActivity.this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            REQUEST_PERMISSION_WRITE_STORAGE);
                } else {
                    mWalletPresenter = new EthereumGenerationPresenter(WalletGenerationActivity.this,
                            mPassword.getText().toString());
                    mWalletPresenter.generateWallet(mPassword.getText().toString());
                    Intent intent = new Intent(WalletGenerationActivity.this, WalletActivity.class);
                    intent.putExtra("WalletAddress", mWalletAddress);
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    public void setPresenter(EthereumGenerationContract.Presenter presenter) {
        mWalletPresenter = presenter;
    }

    @Override
    public void showGeneratedWallet(String address) {
        mWalletAddress = address;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSION_WRITE_STORAGE: {
                if (grantResults.length == 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    finish();
                } else {
                    mWalletPresenter.generateWallet(mPassword.getText().toString());
                }
                break;
            }
        }
    }
}

Step10: Activty class having  textview one for showing wallet address 

public class WalletActivity extends AppCompatActivity {

    private TextView mWalletAddress;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wallet);
        mWalletAddress = (TextView) findViewById(R.id.account_address);
        Bundle extras = getIntent().getExtras();
        mWalletAddress.setText(extras.getString("WalletAddress"));
    }
}

That's it

About Author

Author Image
Keshav Gupta

Keshav Gupta is Android Developer in Oodles, he always look forward for new tasks and new things to learn more.

Request for Proposal

Name is required

Comment is required

Sending message..