pssht  latest
SSH server library written in PHP
Encoder.php
1 <?php
2 
3 /*
4 * This file is part of pssht.
5 *
6 * (c) François Poirotte <clicky@erebot.net>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11 
12 namespace fpoirotte\Pssht\Wire;
13 
17 class Encoder
18 {
20  protected $buffer;
21 
29  public function __construct(\fpoirotte\Pssht\Buffer $buffer = null)
30  {
31  if ($buffer === null) {
32  $buffer = new \fpoirotte\Pssht\Buffer();
33  }
34 
35  $this->buffer = $buffer;
36  }
37 
44  public function getBuffer()
45  {
46  return $this->buffer;
47  }
48 
58  public function encodeBytes($value)
59  {
60  $this->buffer->push($value);
61  return $this;
62  }
63 
73  public function encodeBoolean($value)
74  {
75  return $this->encodeBytes(((bool) $value) ? "\x01" : "\x00");
76  }
77 
87  public function encodeUint32($value)
88  {
89  return $this->encodeBytes(pack('N', $value));
90  }
91 
102  public function encodeUint64($value)
103  {
104  $s = gmp_strval($value, 16);
105  $s = str_pad($s, 16, '0', STR_PAD_LEFT);
106  return $this->encodeBytes(pack('H*', $s));
107  }
108 
118  public function encodeString($value)
119  {
120  $this->encodeUint32(strlen($value));
121  return $this->encodeBytes($value);
122  }
123 
134  public function encodeMpint($value)
135  {
136  if (gmp_cmp($value, "0") == 0) {
137  return $this->encodeString('');
138  }
139  $s = gmp_strval($value, 16);
140  $s = pack('H*', str_pad($s, ((strlen($s) + 1) >> 1) << 1, '0', STR_PAD_LEFT));
141  // Positive numbers where the most significant bit
142  // in the first byte is set must be preceded with \x00
143  // to distinguish them from negative numbers.
144  if ((ord($s[0]) & 0x80) && gmp_sign($value) > 0) {
145  $s = "\x00" . $s;
146  }
147  return $this->encodeString($s);
148  }
149 
159  public function encodeNameList(array $values)
160  {
161  $s = implode(',', $values);
162  if ($s === '') {
163  return $this->encodeUint32(0);
164  }
165 
166  if (addcslashes($s, "\x80..\xFF") !== $s) {
167  throw new \InvalidArgumentException();
168  }
169 
170  // The names in the list MUST NOT be empty.
171  if ($s[0] === ',' || substr($s, -1) === ',' ||
172  strpos($s, ',,') !== false) {
173  throw new \InvalidArgumentException();
174  }
175 
176  return $this->encodeString($s);
177  }
178 }
__construct(\fpoirotte\Pssht\Buffer $buffer=null)
Definition: Encoder.php:29
$buffer
Buffer where the encoded values will be appended.
Definition: Encoder.php:20
encodeNameList(array $values)
Definition: Encoder.php:159