1 min read - Posted 18 Dec 19

Signing Data in Java and Web3j

This code example will demonstrate how to perform an ethereum personal sign operation in java using web3j. This will match signatures generated by the personal sign functions of web3js and geth.

byte[] messageToSign = "Testing Testing 123".getBytes();

//Create prefix
String prefix = "\u0019Ethereum Signed Message:\n" + messageToSign.length;

// Concat prefix and message
ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );

try {
} catch (IOException e) {
    throw new RuntimeException("Error when generating signature", e);

// Hash the prefixed message
byte[] hashedPrefixedMessage = Hash.sha3(outputStream.toByteArray());

// Create credentials (key pair) from mnemonic
Credentials credentials = WalletUtils.loadBip39Credentials("password", "mnemonic");

//Sign the hashed message with the credentials private key
Sign.SignatureData signedMessage = Sign.signMessage(
        hashedPrefixedMessage, credentials.getEcKeyPair(), false);

//Convert sig values from bytes[] to int / hex strings
int sigV = new BigInteger(signedMessage.getV()).intValue();
String hexSigR = Numeric.toHexString(signedMessage.getR());
String hexSigS = Numeric.toHexString(signedMessage.getS());

ecrecover can now be used to verify the message was in fact signed by the expected signee, either within a smart contract or off-chain. Awesome!

Created with Sketch.Content is"CC-BY-SA 4.0" licensed
Article On-chain
Article Author

Craig Williams

Software Developer @ Kauri / ConsenSys




Related Articles
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 involve

Web3j Transaction Managers

A Transaction Manager in Web3j is an abstraction that controls how transactions are signed and broadcast to the Ethereum network, via a connected client. You can pass an implementation to a smart contract wrapper when deploying or loading a contract, or you can use it to directly send transactions in a more manual way. There are multiple different Transaction Manager implementations included, all extending the TransactionManager abstract class. Each extending class must implement the abstract se