Credential.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. namespace blockchain\web3;
  3. use Elliptic\EC;
  4. use kornrunner\Keccak;
  5. use Web3p\EthereumTx\Transaction;
  6. class Credential
  7. {
  8. private $keyPair;
  9. public function __construct($keyPair)
  10. {
  11. $this->keyPair = $keyPair;
  12. }
  13. public function getPublicKey()
  14. {
  15. return $this->keyPair->getPublic()->encode('hex');
  16. }
  17. public function getPrivateKey()
  18. {
  19. return $this->keyPair->getPrivate()->toString(16, 2);
  20. }
  21. public function getAddress()
  22. {
  23. $pubkey = $this->getPublicKey();
  24. return "0x" . substr(Keccak::hash(substr(hex2bin($pubkey), 1), 256), 24);
  25. }
  26. public function signTransaction($raw)
  27. {
  28. $txreq = new Transaction($raw);
  29. $privateKey = $this->getPrivateKey();
  30. $signed = '0x' . $txreq->sign($privateKey);
  31. return $signed;
  32. }
  33. public static function create()
  34. {
  35. $ec = new EC('secp256k1');
  36. $keyPair = $ec->genKeyPair();
  37. return new self($keyPair);
  38. }
  39. public static function fromKey($privateKey)
  40. {
  41. $ec = new EC('secp256k1');
  42. $keyPair = $ec->keyFromPrivate($privateKey);
  43. return new self($keyPair);
  44. }
  45. }