Laravel AT Protocol Client (alpha & unstable)
at main 78 lines 2.0 kB view raw
1<?php 2 3namespace SocialDept\AtpClient\Data; 4 5use phpseclib3\Crypt\Common\PrivateKey; 6use phpseclib3\Crypt\Common\PublicKey; 7use phpseclib3\Crypt\PublicKeyLoader; 8 9class DPoPKey 10{ 11 protected string $privateKeyPem; 12 13 protected string $publicKeyPem; 14 15 public function __construct( 16 PrivateKey|string $privateKey, 17 PublicKey|string $publicKey, 18 public readonly string $keyId, 19 ) { 20 // Store as PEM strings for serialization 21 $this->privateKeyPem = $privateKey instanceof PrivateKey 22 ? $privateKey->toString('PKCS8') 23 : $privateKey; 24 25 $this->publicKeyPem = $publicKey instanceof PublicKey 26 ? $publicKey->toString('PKCS8') 27 : $publicKey; 28 } 29 30 public function getPrivateKey(): PrivateKey 31 { 32 return PublicKeyLoader::load($this->privateKeyPem); 33 } 34 35 public function getPublicKey(): PublicKey 36 { 37 return PublicKeyLoader::load($this->publicKeyPem); 38 } 39 40 public function getPublicJwk(): array 41 { 42 $jwks = json_decode($this->getPublicKey()->toString('JWK'), true); 43 44 // phpseclib returns JWKS format {"keys":[...]}, extract the first key 45 $jwk = $jwks['keys'][0] ?? $jwks; 46 47 return array_merge( 48 $jwk, 49 [ 50 'alg' => 'ES256', 51 'use' => 'sig', 52 'kid' => $this->keyId, 53 ] 54 ); 55 } 56 57 public function getPrivateJwk(): array 58 { 59 $jwks = json_decode($this->getPrivateKey()->toString('JWK'), true); 60 61 // phpseclib returns JWKS format {"keys":[...]}, extract the first key 62 $jwk = $jwks['keys'][0] ?? $jwks; 63 64 return array_merge( 65 $jwk, 66 [ 67 'alg' => 'ES256', 68 'use' => 'sig', 69 'kid' => $this->keyId, 70 ] 71 ); 72 } 73 74 public function toPEM(): string 75 { 76 return $this->privateKeyPem; 77 } 78}