Signature.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace Elliptic\EdDSA;
  3. use Elliptic\Utils;
  4. use BN\BN;
  5. class Signature {
  6. public $eddsa;
  7. /**
  8. * @param {EdDSA} eddsa - eddsa instance
  9. * @param {Array<Bytes>|Object} sig -
  10. * @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes
  11. * @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes
  12. * @param {Array<Bytes>} [sig.Rencoded] - R point encoded
  13. * @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded
  14. */
  15. function __construct($eddsa, $sig) {
  16. $this->eddsa = $eddsa;
  17. if (is_string($sig))
  18. $sig = Utils::parseBytes($sig);
  19. if (is_array($sig) && !isset($sig["R"])) {
  20. $sig = [
  21. "R" => array_slice($sig, 0, $eddsa->encodingLength),
  22. "S" => array_slice($sig, $eddsa->encodingLength)
  23. ];
  24. }
  25. assert($sig["R"] && $sig["S"]); //, 'Signature without R or S');
  26. if ($eddsa->isPoint($sig["R"]))
  27. $this->_R = $sig["R"];
  28. if ($sig["S"] instanceof BN)
  29. $this->_S = $sig["S"];
  30. $this->_Rencoded = is_array($sig["R"]) ? $sig["R"] : (isset($sig["Rencoded"]) ?$sig["Rencoded"] : null);
  31. $this->_Sencoded = is_array($sig["S"]) ? $sig["S"] : (isset($sig["Sencoded"]) ?$sig["Sencoded"] : null);
  32. }
  33. private $_S;
  34. public function S() {
  35. if (!$this->_S) {
  36. $this->_S = $this->eddsa->decodeInt($this->Sencoded());
  37. }
  38. return $this->_S;
  39. }
  40. private $_R;
  41. public function R() {
  42. if (!$this->_R) {
  43. $this->_R = $this->eddsa->decodePoint($this->Rencoded());
  44. }
  45. return $this->_R;
  46. }
  47. private $_Rencoded;
  48. public function Rencoded() {
  49. if (!$this->_Rencoded) {
  50. $this->_Rencoded = $this->eddsa->encodePoint($this->R());
  51. }
  52. return $this->_Rencoded;
  53. }
  54. private $_Sencoded;
  55. public function Sencoded() {
  56. if (!$this->_Sencoded) {
  57. $this->_Sencoded = $this->eddsa->encodeInt($this->S());
  58. }
  59. return $this->_Sencoded;
  60. }
  61. public function toBytes() {
  62. return array_merge($this->Rencoded(), $this->Sencoded());
  63. }
  64. public function toHex() {
  65. return strtoupper(Utils::encode($this->toBytes(), 'hex'));
  66. }
  67. }