summaryrefslogtreecommitdiff
path: root/vendor/aws/aws-sdk-php/src/Crypto/Polyfill/Gmac.php
blob: 535cfcaa09c9d68b2119a99b8974a98b2f3baab6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
<?php
namespace Aws\Crypto\Polyfill;

/**
 * Class Gmac
 *
 * @package Aws\Crypto\Polyfill
 */
class Gmac
{
    use NeedsTrait;

    const BLOCK_SIZE = 16;

    /** @var ByteArray $buf */
    protected $buf;

    /** @var int $bufLength */
    protected $bufLength = 0;

    /** @var ByteArray $h */
    protected $h;

    /** @var ByteArray $hf */
    protected $hf;

    /** @var Key $key */
    protected $key;

    /** @var ByteArray $x */
    protected $x;

    /**
     * Gmac constructor.
     *
     * @param Key $aesKey
     * @param string $nonce
     * @param int $keySize
     */
    public function __construct(Key $aesKey, $nonce, $keySize = 256)
    {
        $this->buf = new ByteArray(16);
        $this->h = new ByteArray(
            \openssl_encrypt(
                \str_repeat("\0", 16),
                "aes-{$keySize}-ecb",
                $aesKey->get(),
                OPENSSL_RAW_DATA | OPENSSL_NO_PADDING
            )
        );
        $this->key = $aesKey;
        $this->x = new ByteArray(16);
        $this->hf = new ByteArray(
            \openssl_encrypt(
                $nonce,
                "aes-{$keySize}-ecb",
                $aesKey->get(),
                OPENSSL_RAW_DATA | OPENSSL_NO_PADDING
            )
        );
    }

    /**
     * Update the object with some data.
     *
     * This method mutates this Gmac object.
     *
     * @param ByteArray $blocks
     * @return self
     */
    public function update(ByteArray $blocks)
    {
        if (($blocks->count() + $this->bufLength) < self::BLOCK_SIZE) {
            // Write to internal buffer until we reach enough to write.
            $this->buf->set($blocks, $this->bufLength);
            $this->bufLength += $blocks->count();
            return $this;
        }

        // Process internal buffer first.
        if ($this->bufLength > 0) {
            // 0 <= state.buf_len < BLOCK_SIZE is an invariant
            $tmp = new ByteArray(self::BLOCK_SIZE);
            $tmp->set($this->buf->slice(0, $this->bufLength));
            $remainingBlockLength = self::BLOCK_SIZE - $this->bufLength;
            $tmp->set($blocks->slice(0, $remainingBlockLength), $this->bufLength);
            $blocks = $blocks->slice($remainingBlockLength);
            $this->bufLength = 0;
            $this->x = $this->blockMultiply($this->x->exclusiveOr($tmp), $this->h);
        }

        // Process full blocks.
        $numBlocks = $blocks->count() >> 4;
        for ($i = 0; $i < $numBlocks; ++$i) {
            $tmp = $blocks->slice($i << 4, self::BLOCK_SIZE);
            $this->x = $this->blockMultiply($this->x->exclusiveOr($tmp), $this->h);
        }
        $last = $numBlocks << 4;

        // Zero-fill buffer
        for ($i = 0; $i < 16; ++$i) {
            $this->buf[$i] = 0;
        }
        // Feed leftover into buffer.
        if ($last < $blocks->count()) {
            $tmp = $blocks->slice($last);
            $this->buf->set($tmp);
            $this->bufLength += ($blocks->count() - $last);
        }
        return $this;
    }

    /**
     * Finish processing the authentication tag.
     *
     * This method mutates this Gmac object (effectively resetting it).
     *
     * @param int $aadLength
     * @param int $ciphertextLength
     * @return ByteArray
     */
    public function finish($aadLength, $ciphertextLength)
    {
        $lengthBlock = new ByteArray(16);
        $state = $this->flush();

        // AES-GCM expects bit lengths, not byte lengths.
        $lengthBlock->set(ByteArray::enc32be($aadLength >> 29), 0);
        $lengthBlock->set(ByteArray::enc32be($aadLength << 3), 4);
        $lengthBlock->set(ByteArray::enc32be($ciphertextLength >> 29), 8);
        $lengthBlock->set(ByteArray::enc32be($ciphertextLength << 3), 12);

        $state->update($lengthBlock);
        $output = $state->x->exclusiveOr($state->hf);

        // Zeroize the internal values as a best-effort.
        $state->buf->zeroize();
        $state->x->zeroize();
        $state->h->zeroize();
        $state->hf->zeroize();
        return $output;
    }

    /**
     * Get a specific bit from the provided array, at the given index.
     *
     * [01234567], 8+[01234567], 16+[01234567], ...
     *
     * @param ByteArray $x
     * @param int $i
     * @return int
     */
    protected function bit(ByteArray $x, $i)
    {
        $byte = $i >> 3;
        return ($x[$byte] >> ((7 - $i) & 7)) & 1;
    }

    /**
     * Galois Field Multiplication
     *
     * This function is the critical path that must be constant-time in order to
     * avoid timing side-channels against AES-GCM.
     *
     * The contents of each are always calculated, regardless of the branching
     * condition, to prevent another kind of timing leak.
     *
     * @param ByteArray $x
     * @param ByteArray $y
     * @return ByteArray
     */
    protected function blockMultiply(ByteArray $x, ByteArray $y)
    {
        static $fieldPolynomial = null;
        if (!$fieldPolynomial) {
            $fieldPolynomial = new ByteArray([
                0xe1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
            ]);
        }
        self::needs($x->count() === 16, 'Argument 1 must be a ByteArray of exactly 16 bytes');
        self::needs($y->count() === 16, 'Argument 2 must be a ByteArray of exactly 16 bytes');

        $v = clone $y;
        $z = new ByteArray(16);

        for ($i = 0; $i < 128; ++$i) {
            // if ($b) $z = $z->exclusiveOr($v);
            $b = $this->bit($x, $i);
            $z = ByteArray::select(
                $b,
                $z->exclusiveOr($v),
                $z
            );

            // if ($b) $v = $v->exclusiveOr($fieldPolynomial);
            $b = $v[15] & 1;
            $v = $v->rshift();
            $v = ByteArray::select(
                $b,
                $v->exclusiveOr($fieldPolynomial),
                $v
            );
        }
        return $z;
    }

    /**
     * Finish processing any leftover bytes in the internal buffer.
     *
     * @return self
     */
    public function flush()
    {
        if ($this->bufLength !== 0) {
            $this->x = $this->blockMultiply(
                $this->x->exclusiveOr($this->buf),
                $this->h
            );
            $this->bufLength = 0;
        }
        return $this;
    }
}