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 
18 {
20  protected $header;
21 
23  protected $main;
24 
25  public function __construct($key)
26  {
27  $this->main = new \fpoirotte\Pssht\Algorithms\ChaCha20(substr($key, 0, 32));
28  $this->header = new \fpoirotte\Pssht\Algorithms\ChaCha20(substr($key, 32));
29  }
30 
31  public function ae($IV, $P, $A)
32  {
33  $polyKey = $this->main->encrypt(str_repeat("\x00", 32), $IV, 0);
34  $poly = new \fpoirotte\Pssht\Algorithms\Poly1305($polyKey);
35  $aad = $this->header->encrypt($A, $IV, 0);
36  $res = $this->main->encrypt($P, $IV, 1);
37  return $aad . $res . $poly->mac($aad . $res);
38  }
39 
40  public function ad($IV, $C, $A, $T)
41  {
42  $len = $this->header->decrypt($A, $IV, 0);
43  if ($C === null && $T === null) {
44  return $len;
45  }
46 
47  $polyKey = $this->main->encrypt(str_repeat("\x00", 32), $IV, 0);
48  $poly = new \fpoirotte\Pssht\Algorithms\Poly1305($polyKey);
49  if ($poly->mac($A . $C) !== $T) {
50  return null;
51  }
52  return $this->main->decrypt($C, $IV, 1);
53  }
54 }
$header
Instance of ChaCha20 used to encrypt/decrypt additional data.
$main
Instance of ChaCha20 used to encrypt/decrypt plaintext/cipher data.