FieldElement.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace ACES\Common\Salsa20;
  3. /**
  4. * FieldElement
  5. *
  6. *
  7. * SplFixedArray with more functions.
  8. *
  9. *
  10. * @author Devi Mandiri <devi.mandiri@gmail.com>
  11. * @link https://github.com/devi/Salt
  12. *
  13. */
  14. class FieldElement extends \SplFixedArray {
  15. public function toString() {
  16. $this->rewind();
  17. $buf = "";
  18. while ($this->valid()) {
  19. $buf .= chr($this->current());
  20. $this->next();
  21. }
  22. $this->rewind();
  23. return $buf;
  24. }
  25. public function toHex() {
  26. $this->rewind();
  27. $hextable = "0123456789ABCDEF";
  28. $buf = "";
  29. while ($this->valid()) {
  30. $c = $this->current();
  31. $buf .= $hextable[$c>>4];
  32. $buf .= $hextable[$c&0x0f];
  33. $this->next();
  34. }
  35. $this->rewind();
  36. return $buf;
  37. }
  38. // compatible to java
  39. public function toHexLowcase(){
  40. $this->rewind();
  41. $hextable = "0123456789abcdef";
  42. $buf = "";
  43. while ($this->valid()) {
  44. $c = $this->current();
  45. $buf .= $hextable[$c>>4];
  46. $buf .= $hextable[$c&0x0f];
  47. $this->next();
  48. }
  49. $this->rewind();
  50. return $buf;
  51. }
  52. public function toBase64() {
  53. return base64_encode($this->toString());
  54. }
  55. public function toJson() {
  56. return json_encode($this->toString());
  57. }
  58. public function slice($offset, $length = null) {
  59. $length = $length ? $length : $this->getSize()-$offset;
  60. $slice = new FieldElement($length);
  61. for ($i = 0;$i < $length;++$i) {
  62. $slice[$i] = $this->offsetGet($i+$offset);
  63. }
  64. return $slice;
  65. }
  66. public function copy($src, $size, $offset = 0, $srcOffset = 0) {
  67. for ($i = 0;$i < $size;++$i) {
  68. $this->offsetSet($i+$offset, $src[$i+$srcOffset]);
  69. }
  70. }
  71. public static function fromArray($array, $save_indexes = true) {
  72. $l = count($array);
  73. $fe = new FieldElement($l);
  74. $array = $save_indexes ? $array : array_values($array);
  75. foreach ($array as $k => $v) $fe[$k] = $v;
  76. return $fe;
  77. }
  78. public static function fromString($str) {
  79. return static::fromArray(unpack("C*", $str), false);
  80. }
  81. public static function fromHex($hex) {
  82. $hex = preg_replace('/[^0-9a-f]/', '', $hex);
  83. return static::fromString(pack("H*", $hex));
  84. }
  85. public static function fromBase64($base64) {
  86. return FieldElement::fromString(base64_decode($base64, true));
  87. }
  88. public static function fromJson($json) {
  89. return FieldElement::fromArray(json_decode($json, true));
  90. }
  91. }