Passed
Push — master ( fbb13e...d759f2 )
by Milad
02:55
created

AbstractEcdsaSigner   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 36
dl 0
loc 70
rs 10
c 1
b 0
f 0
wmc 12

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A getPrivateKey() 0 3 1
A derToSignature() 0 13 1
B decodeDer() 0 28 6
A sign() 0 7 3
1
<?php declare(strict_types=1);
2
3
namespace MiladRahimi\Jwt\Cryptography\Algorithms\Ecdsa;
4
5
use MiladRahimi\Jwt\Cryptography\Keys\EcdsaPrivateKey;
6
use MiladRahimi\Jwt\Cryptography\Signer;
7
use MiladRahimi\Jwt\Exceptions\SigningException;
8
use function ltrim;
9
use function ord;
10
use function str_pad;
11
use function strlen;
12
use function substr;
13
14
abstract class AbstractEcdsaSigner implements Signer
15
{
16
    use Algorithm;
17
18
    protected const ASN1_BIT_STRING = 0x03;
19
20
    protected EcdsaPrivateKey $privateKey;
21
22
    public function __construct(EcdsaPrivateKey $privateKey)
23
    {
24
        $this->privateKey = $privateKey;
25
    }
26
27
    public function sign(string $message): string
28
    {
29
        if (openssl_sign($message, $signature, $this->privateKey->getResource(), $this->algorithm()) === true) {
30
            return $this->derToSignature($signature, $this->keySize());
31
        }
32
33
        throw new SigningException(openssl_error_string() ?: "OpenSSL cannot sign the token.");
34
    }
35
36
    protected function derToSignature(string $der, int $keySize): string
37
    {
38
        $i = $this->decodeDer($der)[0];
39
        [$i, $r] = $this->decodeDer($der, $i);
40
        $s = $this->decodeDer($der, $i)[1];
41
42
        $r = ltrim($r, "\x00");
43
        $s = ltrim($s, "\x00");
44
45
        $r = str_pad($r, $keySize / 8, "\x00", STR_PAD_LEFT);
46
        $s = str_pad($s, $keySize / 8, "\x00", STR_PAD_LEFT);
47
48
        return $r . $s;
49
    }
50
51
    protected function decodeDer(string $der, int $offset = 0): array
52
    {
53
        $pos = $offset;
54
        $size = strlen($der);
55
        $constructed = (ord($der[$pos]) >> 5) & 0x01;
56
        $type = ord($der[$pos++]) & 0x1f;
57
58
        $len = ord($der[$pos++]);
59
        if ($len & 0x80) {
60
            $n = $len & 0x1f;
61
            $len = 0;
62
            while ($n-- && $pos < $size) {
63
                $len = ($len << 8) | ord($der[$pos++]);
64
            }
65
        }
66
67
        if ($type === self::ASN1_BIT_STRING) {
68
            $pos++;
69
            $data = substr($der, $pos, $len - 1);
70
            $pos += $len - 1;
71
        } elseif (!$constructed) {
72
            $data = substr($der, $pos, $len);
73
            $pos += $len;
74
        } else {
75
            $data = '';
76
        }
77
78
        return [$pos, $data];
79
    }
80
81
    public function getPrivateKey(): EcdsaPrivateKey
82
    {
83
        return $this->privateKey;
84
    }
85
}
86