pssht  latest
SSH server library written in PHP
ChaCha20Poly1305.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 
13 
17 class ChaCha20Poly1305 implements \fpoirotte\Pssht\Algorithms\AEAD\AEADInterface
18 {
20  protected $aead;
21 
22  public function __construct($iv, $key)
23  {
24  $this->aead = new \fpoirotte\Pssht\Algorithms\AEAD\ChaCha20Poly1305($key);
25  }
26 
27  public static function getName()
28  {
29  return 'chacha20-poly1305@openssh.com';
30  }
31 
32  public static function getKeySize()
33  {
34  return 512 >> 3;
35  }
36 
37  public static function getIVSize()
38  {
39  return 0;
40  }
41 
42  public static function getBlockSize()
43  {
44  return 1;
45  }
46 
47  public static function getSize()
48  {
49  return 16;
50  }
51 
52  public function encrypt($seqno, $data)
53  {
54  $len = substr($data, 0, 4);
55  $plain = (string) substr($data, 4);
56  $iv = pack('N*', 0, $seqno);
57  return $this->aead->ae($iv, $plain, $len);
58  }
59 
60  public function decrypt($seqno, $data)
61  {
62  $iv = pack('N*', 0, $seqno);
63  if (strlen($data) === 4) {
64  return $this->aead->ad($iv, null, $data, null);
65  }
66 
67  return $this->aead->ad(
68  $iv,
69  (string) substr($data, 4, -static::getSize()), // Cipher
70  substr($data, 0, 4), // AD (length)
71  substr($data, -static::getSize()) // Tag
72  );
73  }
74 }
static getName()
Return the name of the algorithm.
$aead
Underlying implementation for Authenticated Encryption with Additional Data.