Skip to content

Commit c167d1f

Browse files
committed
Add Message Signing page with examples
Signed-off-by: Iker Ruiz de Infante Gonzalez <iker@irzinfante.dev>
1 parent c102a0a commit c167d1f

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

docs/advanced/message_signing.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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+
```

mkdocs.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ nav:
6565
- Ethereum Name Service: advanced/ethereum_name_service.md
6666
- TLS over HTTP and Websockets: advanced/tls_http_websockets.md
6767
- HSM Transaction Signing: advanced/HSM_transaction_signing.md
68+
- Message Signing: advanced/message_signing.md
6869
- Web3j Core Modules: advanced/web3j_core_modules.md
6970
- Json Web Key (JWK) support: advanced/jwk_support.md
7071
- Command Line Tools: command_line_tools.md

0 commit comments

Comments
 (0)