{"content":{"title":"PHP验证TronWeb签名","body":"## 记录下PHP验证TRON签名的坑\r\n\r\nEthereum的验证有很多开源的代码，但是Tron的资料有用的很少，最后参考tronWeb库的代码爬出了深坑\r\n\r\nhttps://github.com/tronprotocol/tronweb/blob/master/src/lib/trx.js#L630\r\n\r\n### 区别：\r\n Message Header \r\n Ethereum:  \\x19Ethereum Signed Message:\\n\r\n Tron:  \\x19TRON Signed Message:\\n32\r\n \r\nSign 结构\r\nEthereum： r,s\r\nTron: recoveryParam, r ,s \r\n\r\n\r\n### 废话不说上代码\r\n```\r\n    public function verify2(string $nonce, string $signature, string $address) : bool\r\n    {\r\n        $message = 'Welcome!\\n\\nThis request will not trigger a blockchain transaction or cost any gas fees.\\n\\nYour authentication status will reset after 24 hours.\\n\\nWallet address:'.$address.'\\n\\nNonce:' . $nonce;\r\n        \r\n        if(substr($address,2) == '0x'){\r\n            $hash = Keccak::hash(sprintf(\"\\x19Ethereum Signed Message:\\n%s%s\", strlen($message), $message), 256);\r\n            $sign   = ['r' => substr($signature, 2, 64), 's' => substr($signature, 66, 64)];\r\n        } else {\r\n            $hash = Keccak::hash(\"\\x19TRON Signed Message:\\n32{$message}\", 256);\r\n            $sign = [\r\n                'recoveryParam' => substr($signature, 130, 2) == '1c' ? 1 : 0,\r\n                'r' => substr($signature, 2, 64),\r\n                's' => substr($signature, 66, 64)\r\n            ];\r\n        }\r\n\r\n        $recid  = ord(hex2bin(substr($signature, 130, 2))) - 27;\r\n\r\n        if ($recid != ($recid & 1)) {\r\n            return false;\r\n        }\r\n\r\n        $publicKey = (new EC('secp256k1'))->recoverPubKey($hash, $sign, $recid);\r\n\r\n        if(substr($address,0,2) == '0x'){\r\n            $recover_address =  '0x' . substr(Keccak::hash(substr(hex2bin($publicKey->encode('hex')), 1), 256), 24);\r\n        } else {\r\n            $recover_address =  '41' . substr(Keccak::hash(substr(hex2bin($publicKey->encode('hex')), 1), 256), 24);\r\n            $address = (new Tron())->address2HexString($address);\r\n        }\r\n\r\n        return hash_equals($recover_address, $address);\r\n    }\r\n```"},"author":{"user":"https://learnblockchain.cn/people/5520","address":null},"history":null,"timestamp":1672216356,"version":1}