summaryrefslogtreecommitdiffstats
path: root/vendor/minishlink/web-push/src/Utils.php
blob: bd7f6c49e814b5b3bf061cdc3e2f1e0d627a10a1 (plain) (blame)
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
<?php

declare(strict_types=1);

/*
 * This file is part of the WebPush library.
 *
 * (c) Louis Lagrange <lagrange.louis@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Minishlink\WebPush;

use Jose\Component\Core\Util\Ecc\PublicKey;

class Utils
{
    /**
     * @param string $value
     *
     * @return int
     */
    public static function safeStrlen(string $value): int
    {
        return mb_strlen($value, '8bit');
    }

    /**
     * @param PublicKey $publicKey
     *
     * @return string
     */
    public static function serializePublicKey(PublicKey $publicKey): string
    {
        $hexString = '04';
        $hexString .= str_pad(gmp_strval($publicKey->getPoint()->getX(), 16), 64, '0', STR_PAD_LEFT);
        $hexString .= str_pad(gmp_strval($publicKey->getPoint()->getY(), 16), 64, '0', STR_PAD_LEFT);

        return $hexString;
    }

    /**
     * @param string $data
     *
     * @return array
     */
    public static function unserializePublicKey(string $data): array
    {
        $data = bin2hex($data);
        if (mb_substr($data, 0, 2, '8bit') !== '04') {
            throw new \InvalidArgumentException('Invalid data: only uncompressed keys are supported.');
        }
        $data = mb_substr($data, 2, null, '8bit');
        $dataLength = self::safeStrlen($data);

        return [
            hex2bin(mb_substr($data, 0, $dataLength / 2, '8bit')),
            hex2bin(mb_substr($data, $dataLength / 2, null, '8bit')),
        ];
    }
}