Laravel AT Protocol Client (alpha & unstable)
1<?php
2
3namespace SocialDept\AtpClient\Storage;
4
5use Illuminate\Contracts\Encryption\Encrypter;
6use SocialDept\AtpClient\Contracts\KeyStore;
7use SocialDept\AtpClient\Data\DPoPKey;
8
9class EncryptedFileKeyStore implements KeyStore
10{
11 public function __construct(
12 protected string $storagePath,
13 protected ?Encrypter $encrypter = null,
14 ) {
15 $this->encrypter = $this->encrypter ?? app('encrypter');
16
17 if (! is_dir($this->storagePath)) {
18 mkdir($this->storagePath, 0755, true);
19 }
20 }
21
22 public function store(string $sessionId, DPoPKey $key): void
23 {
24 $data = [
25 'privateKey' => $key->toPEM(),
26 'publicKey' => $key->getPublicKey()->toString('PKCS8'),
27 'keyId' => $key->keyId,
28 ];
29
30 $encrypted = $this->encrypter->encrypt($data);
31
32 file_put_contents(
33 $this->getKeyPath($sessionId),
34 $encrypted
35 );
36 }
37
38 public function get(string $sessionId): ?DPoPKey
39 {
40 $path = $this->getKeyPath($sessionId);
41
42 if (! file_exists($path)) {
43 return null;
44 }
45
46 $encrypted = file_get_contents($path);
47 $data = $this->encrypter->decrypt($encrypted);
48
49 return new DPoPKey(
50 privateKey: $data['privateKey'],
51 publicKey: $data['publicKey'],
52 keyId: $data['keyId'],
53 );
54 }
55
56 public function delete(string $sessionId): void
57 {
58 $path = $this->getKeyPath($sessionId);
59
60 if (file_exists($path)) {
61 unlink($path);
62 }
63 }
64
65 public function exists(string $sessionId): bool
66 {
67 return file_exists($this->getKeyPath($sessionId));
68 }
69
70 protected function getKeyPath(string $sessionId): string
71 {
72 return $this->storagePath.'/'.hash('sha256', $sessionId).'.key';
73 }
74}