3

How can i verify Ethereum signed messase with PHP?

Message is signed using web3.personal.sign function in Web3.js and signature is then sent to server. How can I verify it with PHP?

Are there some pre-built packages (on Packagist) or I should do this from scratch? Is it possible to do this without any connection to RPC nodes or chain (off-chain)?

I already found some question about this on Ethereum StackExchange, but it is very complicate and a bit old so I want to know if there is newer and better solution.

I also found some package on GitHub, but I don't know if it will work with web3.personal.sign.

Some links I found:

TylerH
  • 20,799
  • 66
  • 75
  • 101
Filip Š
  • 746
  • 2
  • 13
  • 22

2 Answers2

9

Verifying signed message is possible with package php-ecrecover.

You can get the original message address using this package and then verify if it is same as expected address.

JS Sign:

let message = 'Hello World!'
let address = web3.eth.coinbase

web3.personal.sign(web3.fromUtf8(message), address, console.log);

PHP Verify:

$address = '0xe12Aa5FB5659bb0DB3f488e29701fE303bcBAf65';
$message = 'Hello World!';
$signed = '0x2cb6b41177a5e6690ebbc61f182758fcf8f54403edcb848fc1089a772227d55163804b4dc7fcf72d15f0d977d741f6dd6bcc4fc4c74916378afcad06be77b2101b';

if ($address == personal_ecRecover($message, $signed)) {
    echo 'Message verified';
} else {
    echo 'Message not verified';
}
Filip Š
  • 746
  • 2
  • 13
  • 22
  • 1
    Update: a newer and maintained package is also available which supports this. https://github.com/simplito/elliptic-php#verifying-ethereum-signature – mllnd Dec 13 '19 at 23:45
1

There is stripped-down version of the php-ecrecover functions for only this purpose in a single file.

Gets the public address from a personal signed message ( like web3.eth.sign ). First argument is the original message, second is the signed value sent to the server. The returned value in the form "0x705..." is the public address that signed the message.

require_once("ecrecover-simple.php");

$addr = \ECRecoverSimple\fromMessage(
     //Original message
    "Sign-In",
     //Signed message 
    "0xe4ad6b81ebd40bcd7420e95c7e5c88c64ba3fed80a06067078af7e0a9457f5a6728005fcab5d5abf80d5bed4bccae63338de0f0f369197d8dd12ee1b704c8ffe1c"
);

File is published here: https://github.com/marcmasmar/php-ecrecover-simple

Note: This provides a peculiar and 64bit only alternative for the already valid answer. It might help in lightweight scenarios and without the ability or will to run Composer.

Marc Masip
  • 11
  • 3
  • 1
    @JeremyCaney, and Sangwin Gawande: Thank you for the advices. Added how it can answer because originally I only wanted to add a discrete comment with the alternative version. – Marc Masip Jul 04 '23 at 05:52