androidweb3jsweb3-java

Signatures different in web3j and web3js?


I am using web3J version "org.web3j:core:4.6.0" and get following problem. When I sign the same raw message (a string) I get different signatures using web3js and web3j. The signature from web3js is valid (and web3j is not), I test it using solidity ecrecover function. It's worth to mention that hashes as you can see in the snippets are the same.

Java Code (web3j).

String private_key = "25218ba6de76757feba214961b588345e1415b267383af9fda13dd032ae75fff";
Credentials credentials1 = Credentials.create(privateKey1)


String message = "0x12cf1496120ada41033631fd6fa12613416c18696b70e4b072b3d1157ee165c7";

Sign.SignatureData signature = Sign.signMessage(message.getBytes(), credentials.getEcKeyPair());

String signature_V = Numeric.toHexString(signature.getV());
String signature_R = Numeric.toHexString(signature.getR());
String signature_S = Numeric.toHexString(signature.getS());

java code result -

signature_V=: 0x1b
signature_R=: 0x9f09f364e24577eb9dde9f1e3e2c0db0473fdd03e38945de0a5d97a92ee9b5c1
signature_S=: 0x3d7860741f64144ac8317880dc110ffadf020f712322f7c11bcf9cf3e446c212

using web3js code.

let privateKey = "25218ba6de76757feba214961b588345e1415b267383af9fda13dd032ae75fff"
let message = "0x12cf1496120ada41033631fd6fa12613416c18696b70e4b072b3d1157ee165c7";

let sign = web3.eth.accounts.sign(message, privateKey); 

web3js result -

signature_V=: 0x1b
signature_R=: 0x3db7bc52699c3b34d9b8b617c5e7646ce5b6899d278c061cf83dcd216316f0ef
signature_S=: 0x0dea9a606165cb7fc3e4b7959ba43f33025b44886c6363cd4d7788297a1cbf39

Solution

  • First of all, using your js sample and latest web3 lib (1.3.0) I get these results:

    1. Web3js sample

    enter image description here


    Then, in your java code you need to use signPrefixedMessage, because web3js version wraps input message, hashes it and only then signs. Also if message in hex, web3js properly converts it to byte array, you just used bytes of string. As result I received two identical signatures.

    1. Web3j sample (kotlin)

    enter image description here