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