| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
/* |
| 6 |
* The MIT License (MIT) |
| 7 |
* |
| 8 |
* Copyright (c) 2014-2021 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 Cose\Key; |
| 15 |
|
| 16 |
use function array_key_exists; |
| 17 |
use Assert\Assertion; |
| 18 |
|
| 19 |
class Key |
| 20 |
{ |
| 21 |
public const TYPE = 1; |
| 22 |
public const TYPE_OKP = 1; |
| 23 |
public const TYPE_EC2 = 2; |
| 24 |
public const TYPE_RSA = 3; |
| 25 |
public const TYPE_OCT = 4; |
| 26 |
public const KID = 2; |
| 27 |
public const ALG = 3; |
| 28 |
public const KEY_OPS = 4; |
| 29 |
public const BASE_IV = 5; |
| 30 |
|
| 31 |
/** |
| 32 |
* @var array |
| 33 |
*/ |
| 34 |
private $data; |
| 35 |
|
| 36 |
public function __construct(array $data) |
| 37 |
{ |
| 38 |
Assertion::keyExists($data, self::TYPE, 'Invalid key: the type is not defined'); |
| 39 |
$this->data = $data; |
| 40 |
} |
| 41 |
|
| 42 |
public static function createFromData(array $data): self |
| 43 |
{ |
| 44 |
Assertion::keyExists($data, self::TYPE, 'Invalid key: the type is not defined'); |
| 45 |
switch ($data[self::TYPE]) { |
| 46 |
case 1: |
| 47 |
return new OkpKey($data); |
| 48 |
case 2: |
| 49 |
return new Ec2Key($data); |
| 50 |
case 3: |
| 51 |
return new RsaKey($data); |
| 52 |
case 4: |
| 53 |
return new SymmetricKey($data); |
| 54 |
default: |
| 55 |
return new self($data); |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
/** |
| 60 |
* @return int|string |
| 61 |
*/ |
| 62 |
public function type() |
| 63 |
{ |
| 64 |
return $this->data[self::TYPE]; |
| 65 |
} |
| 66 |
|
| 67 |
public function alg(): int |
| 68 |
{ |
| 69 |
return (int) $this->get(self::ALG); |
| 70 |
} |
| 71 |
|
| 72 |
public function getData(): array |
| 73 |
{ |
| 74 |
return $this->data; |
| 75 |
} |
| 76 |
|
| 77 |
public function has(int $key): bool |
| 78 |
{ |
| 79 |
return array_key_exists($key, $this->data); |
| 80 |
} |
| 81 |
|
| 82 |
/** |
| 83 |
* @return mixed |
| 84 |
*/ |
| 85 |
public function get(int $key) |
| 86 |
{ |
| 87 |
Assertion::keyExists($this->data, $key, sprintf('The key has no data at index %d', $key)); |
| 88 |
|
| 89 |
return $this->data[$key]; |
| 90 |
} |
| 91 |
} |
| 92 |
|