pssht  latest
SSH server library written in PHP
AES128GCM.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 AES128GCM implements
18  \fpoirotte\Pssht\Algorithms\AEAD\AEADInterface,
19  \fpoirotte\Pssht\Algorithms\AvailabilityInterface
20 {
22  protected $iv;
23 
25  protected $gcm;
26 
27  public function __construct($iv, $key)
28  {
29  $this->iv = gmp_init(bin2hex($iv), 16);
30  $this->gcm = new \fpoirotte\Pssht\Algorithms\AEAD\GCM(
31  MCRYPT_RIJNDAEL_128,
32  $key,
33  128
34  );
35  }
36 
37  public static function getName()
38  {
39  return 'aes128-gcm@openssh.com';
40  }
41 
42  public static function getKeySize()
43  {
44  return 128 >> 3;
45  }
46 
47  public static function getIVSize()
48  {
49  return 12; // 96 bits
50  }
51 
52  public static function getBlockSize()
53  {
54  return 16; // 128 bits
55  }
56 
57  public static function getSize()
58  {
59  return 16; // 128 bits
60  }
61 
62  public function encrypt($seqno, $data)
63  {
64  $len = substr($data, 0, 4);
65  $plain = (string) substr($data, 4);
66  $iv = str_pad(gmp_strval($this->iv, 16), 24, '0', STR_PAD_LEFT);
67  $res = $this->gcm->ae(pack('H*', $iv), $plain, $len);
68  $this->iv = \fpoirotte\Pssht\Algorithms\AEAD\GCM::inc($this->iv, 64);
69  return $len . $res[0] . $res[1];
70  }
71 
72  public function decrypt($seqno, $data)
73  {
74  if (strlen($data) === 4) {
75  return $data;
76  }
77 
78  $len = substr($data, 0, 4);
79  $cipher = (string) substr($data, 4, -static::getSize());
80  $tag = substr($data, -static::getSize());
81  $iv = str_pad(gmp_strval($this->iv, 16), 24, '0', STR_PAD_LEFT);
82  $res = $this->gcm->ad(pack('H*', $iv), $cipher, $len, $tag);
83  $this->iv = \fpoirotte\Pssht\Algorithms\AEAD\GCM::inc($this->iv, 64);
84  return $res;
85  }
86 
87  final public static function isAvailable()
88  {
89  if (!extension_loaded('mcrypt')) {
90  return false;
91  }
92 
93  if (!defined('MCRYPT_RIJNDAEL_128')) {
94  return false;
95  }
96  $res = @mcrypt_module_open(
97  MCRYPT_RIJNDAEL_128,
98  '',
99  'ecb',
100  ''
101  );
102  if ($res !== false) {
103  mcrypt_module_close($res);
104  }
105  return (bool) $res;
106  }
107 }
$gcm
Underlying GCM implementation.
Definition: AES128GCM.php:25
static getName()
Return the name of the algorithm.
Definition: AES128GCM.php:37