|
| 1 | +Message Signing |
| 2 | +=============== |
| 3 | + |
| 4 | +Web3j can sign arbitrary-sized messages in the `personal_sign` style (see [EIP-191](https://eips.ethereum.org/EIPS/eip-191)), via the `signPrefixedMessage` method of the `Sign` class. This allows you to sign a message, obtain the signature as a `SignatureData` type object (containing the `r`, `s` and `v` components of the signature), and recover the signer's public key or address from the signature and the original message. |
| 5 | + |
| 6 | +## Usage |
| 7 | + |
| 8 | +Here is a complete usage example: |
| 9 | + |
| 10 | +```java |
| 11 | +// Create a signer from a private key |
| 12 | +Credentials credentials = Credentials.create("<private key>"); |
| 13 | + |
| 14 | +// Sign the message |
| 15 | +String message = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks"; |
| 16 | +SignatureData signatureData = Sign.signPrefixedMessage(message.getBytes(StandardCharsets.UTF_8), credentials.getEcKeyPair()); |
| 17 | + |
| 18 | +// Recover the signer's public key and convert it to address |
| 19 | +BigInteger ecPubKey = Sign.signedPrefixedMessageToKey(message.getBytes(), signatureData); |
| 20 | +String address = Numeric.prependHexPrefix(Keys.getAddress(ecPubKey)); |
| 21 | + |
| 22 | +// Check if the signer’s address matches the recovered address |
| 23 | +address.equals(credentials.getAddress()); // true |
| 24 | +``` |
| 25 | + |
| 26 | +### Obtain signature hex string |
| 27 | + |
| 28 | +By concatenating the components of the signature from the `signatureData` object, you can obtain the signature as a hexadecimal string as follows: |
| 29 | + |
| 30 | +```java |
| 31 | +byte[] signature = new byte[65]; |
| 32 | +System.arraycopy(signatureData.getR(), 0, signature, 0, 32); |
| 33 | +System.arraycopy(signatureData.getS(), 0, signature, 32, 32); |
| 34 | +System.arraycopy(signatureData.getV(), 0, signature, 64, 1); |
| 35 | + |
| 36 | +Numeric.toHexString(signature); // "0x..." |
| 37 | +``` |
0 commit comments