1010use RuntimeException ;
1111use SplFileObject ;
1212
13- class EdDSASignerKey implements Loader, Generator
13+ class EdDSASignerKey implements Loader
1414{
1515 public const KEY_LENGTH = SODIUM_CRYPTO_SIGN_KEYPAIRBYTES ;
1616 public const PUBLIC_KEY_LENGTH = SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES ;
@@ -21,13 +21,8 @@ class EdDSASignerKey implements Loader, Generator
2121 private static string $ privateKey ;
2222 private static string $ publicKey ;
2323
24- public function __construct (
25- private readonly Repository $ config ,
26- private readonly LoggerInterface $ logger ,
27- ) {
28- }
2924
30- public static function init (Repository $ config , LoggerInterface $ logger ): static
25+ public static function make (Repository $ config , LoggerInterface $ logger ): static
3126 {
3227 if (!isset (static ::$ publicKey , static ::$ privateKey )) {
3328 $ path = $ config ->get (static ::CONFIG_KEY_PATH );
@@ -39,7 +34,7 @@ public static function init(Repository $config, LoggerInterface $logger): static
3934 [static ::$ publicKey , static ::$ privateKey ] = static ::parseKeys ($ path , $ logger );
4035 }
4136
42- return new static ($ config , $ logger );
37+ return new static ();
4338 }
4439
4540 protected static function parseKeys (string $ keyPath , LoggerInterface $ logger ): array
@@ -71,55 +66,5 @@ public function getKey(): string|array
7166 return [self ::$ publicKey , self ::$ privateKey ];
7267 }
7368
74- public function generate (?string $ write ): ?string
75- {
76- $ keyPair = sodium_crypto_sign_keypair ();
77- $ privateKey = bin2hex (sodium_crypto_sign_secretkey ($ keyPair ));
78- $ publicKey = bin2hex (sodium_crypto_sign_publickey ($ keyPair ));
79-
80- $ key = implode (PHP_EOL , [$ publicKey , $ privateKey ]);
81-
82- if ($ write === null ) {
83- return $ key ;
84- }
85-
86- $ path = $ this ->config ->get (self ::CONFIG_KEY_PATH );
87-
88- if ($ path === null ) {
89- throw new RuntimeException ('File for EdDSA signer is not set ' );
90- }
91-
92- if (!@file_exists ($ concurrentDirectory = dirname ($ path )) && !@mkdir (
93- $ concurrentDirectory ,
94- 0740 ,
95- true
96- ) && !is_dir (
97- $ concurrentDirectory
98- )) {
99- throw new RuntimeException (sprintf ('Directory "%s" was not created ' , $ concurrentDirectory ));
100- }
101-
102- $ file = new SplFileObject ($ path , 'wb ' );
10369
104- if ($ file ->flock (LOCK_EX ) === false ) {
105- throw new RuntimeException ('Error while locking file (exclusive/writing) ' );
106- }
107-
108- try {
109- if ($ file ->fwrite ($ key ) === false ) {
110- throw new RuntimeException ('Error while writing public key to file ' );
111- }
112- } finally {
113- if ($ file ->flock (LOCK_UN ) === false ) {
114- $ this ->logger ->warning ('Error while unlocking file ' );
115- }
116-
117- sodium_memzero ($ privateKey );
118- sodium_memzero ($ publicKey );
119- sodium_memzero ($ keyPair );
120- sodium_memzero ($ key );
121- }
122-
123- return null ;
124- }
12570}
0 commit comments