Completed
Push — master ( 7acc61...cd9e85 )
by Florent
22s
created

SignatureRequest::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2018 Spomky-Labs
9
 *
10
 * This software may be modified and distributed under the terms
11
 * of the MIT license.  See the LICENSE file for details.
12
 */
13
14
namespace U2FAuthentication\Fido;
15
16
use Base64Url\Base64Url;
17
18
class SignatureRequest implements \JsonSerializable
19
{
20
    /**
21
     * @var string
22
     */
23
    private $applicationId;
24
25
    /**
26
     * @var string
27
     */
28
    private $challenge;
29
30
    /**
31
     * @var RegisteredKey[]
32
     */
33
    private $registeredKeys = [];
34
35
    /**
36
     * @param RegisteredKey[] $registeredKeys
37
     */
38
    public function __construct(string $applicationId, array $registeredKeys)
39
    {
40
        $this->applicationId = $applicationId;
41
        foreach ($registeredKeys as $registeredKey) {
42
            if (!$registeredKey instanceof RegisteredKey) {
43
                throw new \InvalidArgumentException('Invalid registered keys list.');
44
            }
45
            $this->registeredKeys[Base64Url::encode((string) $registeredKey->getKeyHandler())] = $registeredKey;
46
        }
47
        $this->challenge = random_bytes(32);
48
    }
49
50
    public function addRegisteredKey(RegisteredKey $registeredKey): void
51
    {
52
        $this->registeredKeys[Base64Url::encode((string) $registeredKey->getKeyHandler())] = $registeredKey;
53
    }
54
55
    public function hasRegisteredKey(KeyHandler $keyHandle): bool
56
    {
57
        return array_key_exists(Base64Url::encode($keyHandle->getValue()), $this->registeredKeys);
58
    }
59
60
    public function getRegisteredKey(KeyHandler $keyHandle): RegisteredKey
61
    {
62
        if (!$this->hasRegisteredKey($keyHandle)) {
63
            throw new \InvalidArgumentException('Unsupported key handle.');
64
        }
65
66
        return $this->registeredKeys[Base64Url::encode($keyHandle->getValue())];
67
    }
68
69
    public function getApplicationId(): string
70
    {
71
        return $this->applicationId;
72
    }
73
74
    public function getChallenge(): string
75
    {
76
        return $this->challenge;
77
    }
78
79
    /**
80
     * @return RegisteredKey[]
81
     */
82
    public function getRegisteredKeys(): array
83
    {
84
        return $this->registeredKeys;
85
    }
86
87
    public function jsonSerialize(): array
88
    {
89
        return [
90
            'appId' => $this->applicationId,
91
            'challenge' => Base64Url::encode($this->challenge),
92
            'registeredKeys' => array_values($this->registeredKeys),
93
        ];
94
    }
95
}
96