Signing an Ethereum Transaction in Web3j

Web3j provides a bunch of helper classes to enable you to create and sign a transaction within your ethereum java code.

The transaction creation process involves a number of steps including obtaining the nonce for the sending user, and defining gas values. An example code snippet is provided below:

//Connect to node. Defaults to http://localhost:8545
Web3j web3 = Web3j.build(new HttpService());

//Generate wallet credentials from a mnemonic seed phrase
Credentials credentials = WalletUtils.loadBip39Credentials("password", "mnemonic");

//The transaction recipient address
String toAddress = "0xF0f15Cedc719B5A55470877B0710d5c7816916b1";

//The wei amount to transfer (1 ether)
BigInteger amountToTransferInWei = Convert.toWei(
        BigDecimal.ONE, Convert.Unit.ETHER).toBigInteger();

// Get nonce
BigInteger nonce = web3.ethGetTransactionCount(
        credentials.getAddress(), DefaultBlockParameterName.LATEST).send()
        .getTransactionCount();

// Gas Parameters
// Gas required for a standard ether transfer transaction
BigInteger gasLimit = BigInteger.valueOf(21000);
// 1 Gwei = 1,000,000,000 wei
BigInteger gasPrice = Convert.toWei(
        BigDecimal.ONE, Convert.Unit.GWEI).toBigInteger();

// Prepare the rawTransaction
RawTransaction rawTransaction  = RawTransaction.createEtherTransaction(
        nonce,
        gasPrice,
        gasLimit,
        toAddress,
        amountToTransferInWei);

// Sign the transaction
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
String hexSignedMessage = Numeric.toHexString(signedMessage);

Thanks to Greg Jeanmart, and the article Managing an Ethereum Account with Java and Web3j.