Add Keccak256 sha3 usage.
This commit is contained in:
parent
ffb02edee7
commit
02b30ee2d5
@ -11,7 +11,9 @@
|
|||||||
],
|
],
|
||||||
"minimum-stability": "dev",
|
"minimum-stability": "dev",
|
||||||
"require": {
|
"require": {
|
||||||
"guzzlehttp/guzzle": "~6.0"
|
"guzzlehttp/guzzle": "~6.0",
|
||||||
|
"PHP": "^7.1",
|
||||||
|
"kornrunner/keccak": "dev-master"
|
||||||
},
|
},
|
||||||
"require-dev": {
|
"require-dev": {
|
||||||
"phpunit/phpunit": "~6.0"
|
"phpunit/phpunit": "~6.0"
|
||||||
|
@ -1,11 +1,28 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This file is part of web3.php package.
|
||||||
|
*
|
||||||
|
* (c) Kuan-Cheng,Lai <alk03073135@gmail.com>
|
||||||
|
*
|
||||||
|
* @author Peter Lai <alk03073135@gmail.com>
|
||||||
|
* @license MIT
|
||||||
|
*/
|
||||||
|
|
||||||
namespace Web3;
|
namespace Web3;
|
||||||
|
|
||||||
use InvalidArgumentException;
|
use InvalidArgumentException;
|
||||||
|
use kornrunner\Keccak;
|
||||||
|
|
||||||
class Utils
|
class Utils
|
||||||
{
|
{
|
||||||
|
/**
|
||||||
|
* SHA3_NULL_HASH
|
||||||
|
*
|
||||||
|
* @const string
|
||||||
|
*/
|
||||||
|
const SHA3_NULL_HASH = 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* construct
|
* construct
|
||||||
*
|
*
|
||||||
@ -49,4 +66,27 @@ class Utils
|
|||||||
|
|
||||||
return pack('H*', $hexString);
|
return pack('H*', $hexString);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* sha3
|
||||||
|
* keccak256
|
||||||
|
*
|
||||||
|
* @param string $value
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function sha3($value)
|
||||||
|
{
|
||||||
|
if (!is_string($value)) {
|
||||||
|
throw new InvalidArgumentException('The value to sha3 function must be string.');
|
||||||
|
}
|
||||||
|
if (preg_match('/^0x/', $value) > 0) {
|
||||||
|
$value = self::hexToBin($value);
|
||||||
|
}
|
||||||
|
$hash = Keccak::hash($value, 256);
|
||||||
|
|
||||||
|
if ($hash === self::SHA3_NULL_HASH) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return '0x' . $hash;
|
||||||
|
}
|
||||||
}
|
}
|
@ -62,4 +62,20 @@ class UtilsTest extends TestCase
|
|||||||
|
|
||||||
$this->assertEquals($str, '七彩神仙鱼');
|
$this->assertEquals($str, '七彩神仙鱼');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* testSha3
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function testSha3()
|
||||||
|
{
|
||||||
|
$str = Utils::sha3('');
|
||||||
|
|
||||||
|
$this->assertNull($str);
|
||||||
|
|
||||||
|
$str = Utils::sha3('baz(uint32,bool)');
|
||||||
|
|
||||||
|
$this->assertEquals(mb_substr($str, 0, 10), '0xcdcd77c0');
|
||||||
|
}
|
||||||
}
|
}
|
Loading…
Reference in New Issue
Block a user