Laravel AT Protocol Client (alpha & unstable)
1<?php
2
3namespace SocialDept\AtpClient\Crypto;
4
5use Illuminate\Contracts\Support\Arrayable;
6use Illuminate\Contracts\Support\Jsonable;
7use phpseclib3\Crypt\EC\PrivateKey;
8use phpseclib3\Crypt\EC\PublicKey;
9use Stringable;
10
11class JsonWebKey implements Arrayable, Jsonable, Stringable
12{
13 protected PrivateKey|PublicKey $key;
14
15 protected string $kid = 'key-1';
16
17 public function __construct(PrivateKey|PublicKey $key)
18 {
19 $this->key = $key;
20 }
21
22 /**
23 * Get the underlying key
24 */
25 public function key(): PrivateKey|PublicKey
26 {
27 return $this->key;
28 }
29
30 /**
31 * Get public key version
32 */
33 public function asPublic(): static
34 {
35 if ($this->key instanceof PrivateKey) {
36 $clone = clone $this;
37 $clone->key = $this->key->getPublicKey();
38
39 return $clone;
40 }
41
42 return $this;
43 }
44
45 /**
46 * Get key ID
47 */
48 public function kid(): string
49 {
50 return $this->kid;
51 }
52
53 /**
54 * Set key ID
55 */
56 public function withKid(string $kid): static
57 {
58 $this->kid = $kid;
59
60 return $this;
61 }
62
63 /**
64 * Export as PEM
65 */
66 public function toPEM(): string
67 {
68 return $this->key->toString('PKCS8');
69 }
70
71 /**
72 * Convert to array (JWK format)
73 */
74 public function toArray(): array
75 {
76 $jwk = $this->key->getPublicKey()->toString('JWK');
77
78 return array_merge(
79 json_decode($jwk, true),
80 [
81 'alg' => P256::ALG,
82 'use' => 'sig',
83 'kid' => $this->kid(),
84 ]
85 );
86 }
87
88 /**
89 * Convert to JSON
90 */
91 public function toJson($options = 0): string
92 {
93 return json_encode($this->toArray(), JSON_THROW_ON_ERROR | $options);
94 }
95
96 /**
97 * Convert to string
98 */
99 public function __toString(): string
100 {
101 return $this->toJson();
102 }
103}