Laravel AT Protocol Client (alpha & unstable)
1<?php
2
3namespace SocialDept\AtpClient\Crypto;
4
5use phpseclib3\Crypt\EC;
6use phpseclib3\Crypt\EC\PrivateKey;
7use phpseclib3\Crypt\EC\PublicKey;
8use phpseclib3\Crypt\PublicKeyLoader;
9
10abstract class AbstractKeypair
11{
12 const CURVE = '';
13
14 const ALG = '';
15
16 const MULTIBASE_PREFIX = '';
17
18 protected PrivateKey|PublicKey $key;
19
20 /**
21 * Create a new keypair
22 */
23 public static function create(): static
24 {
25 $self = new static;
26 $self->key = EC::createKey(static::CURVE);
27
28 return $self;
29 }
30
31 /**
32 * Load keypair from base64-encoded private key
33 */
34 public static function load(?string $private = null): static
35 {
36 $self = new static;
37 $self->key = PublicKeyLoader::load(
38 base64_decode(strtr($private, '-_', '+/'), strict: true)
39 );
40
41 return $self;
42 }
43
44 /**
45 * Get the key instance
46 */
47 public function key(): PrivateKey|PublicKey
48 {
49 return $this->key;
50 }
51
52 /**
53 * Export private key as base64-encoded string
54 */
55 public function privateB64(): string
56 {
57 return strtr(base64_encode($this->key->toString('PKCS8')), '+/', '-_');
58 }
59
60 /**
61 * Export private key as PEM string
62 */
63 public function toPEM(): string
64 {
65 return $this->key->toString('PKCS8');
66 }
67
68 /**
69 * Convert to JSON Web Key format
70 */
71 public function toJWK(): JsonWebKey
72 {
73 return new JsonWebKey($this->key);
74 }
75}