@@ -60,7 +60,12 @@ public static function validate(array $vapid): array
6060 gmp_init (bin2hex (Base64Url::decode ($ jwk ->get ('x ' ))), 16 ),
6161 gmp_init (bin2hex (Base64Url::decode ($ jwk ->get ('y ' ))), 16 )
6262 ));
63- $ vapid ['publicKey ' ] = base64_encode (hex2bin (Utils::serializePublicKey ($ publicKey )));
63+
64+ $ binaryPublicKey = hex2bin (Utils::serializePublicKey ($ publicKey ));
65+ if (!$ binaryPublicKey ) {
66+ throw new \ErrorException ('Failed to convert VAPID public key from hexadecimal to binary ' );
67+ }
68+ $ vapid ['publicKey ' ] = base64_encode ($ binaryPublicKey );
6469 $ vapid ['privateKey ' ] = base64_encode (str_pad (Base64Url::decode ($ jwk ->get ('d ' )), 2 * self ::PRIVATE_KEY_LENGTH , '0 ' , STR_PAD_LEFT ));
6570 }
6671
@@ -122,6 +127,9 @@ public static function getVapidHeaders(string $audience, string $subject, string
122127 'exp ' => $ expiration ,
123128 'sub ' => $ subject ,
124129 ], JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK );
130+ if (!$ jwtPayload ) {
131+ throw new \ErrorException ('Failed to encode JWT payload in JSON ' );
132+ }
125133
126134 list ($ x , $ y ) = Utils::unserializePublicKey ($ publicKey );
127135 $ jwk = JWK ::create ([
@@ -163,16 +171,27 @@ public static function getVapidHeaders(string $audience, string $subject, string
163171 * DO NOT create keys at each initialization! Save those keys and reuse them.
164172 *
165173 * @return array
174+ * @throws \ErrorException
166175 */
167176 public static function createVapidKeys (): array
168177 {
169178 $ curve = NistCurve::curve256 ();
170179 $ privateKey = $ curve ->createPrivateKey ();
171180 $ publicKey = $ curve ->createPublicKey ($ privateKey );
172181
182+ $ binaryPublicKey = hex2bin (Utils::serializePublicKey ($ publicKey ));
183+ if (!$ binaryPublicKey ) {
184+ throw new \ErrorException ('Failed to convert VAPID public key from hexadecimal to binary ' );
185+ }
186+
187+ $ binaryPrivateKey = hex2bin (str_pad (gmp_strval ($ privateKey ->getSecret (), 16 ), 2 * self ::PRIVATE_KEY_LENGTH , '0 ' , STR_PAD_LEFT ));
188+ if (!$ binaryPrivateKey ) {
189+ throw new \ErrorException ('Failed to convert VAPID private key from hexadecimal to binary ' );
190+ }
191+
173192 return [
174- 'publicKey ' => base64_encode (hex2bin (Utils:: serializePublicKey ( $ publicKey )) ),
175- 'privateKey ' => base64_encode (hex2bin ( str_pad ( gmp_strval ( $ privateKey -> getSecret (), 16 ), 2 * self :: PRIVATE_KEY_LENGTH , ' 0 ' , STR_PAD_LEFT )) )
193+ 'publicKey ' => base64_encode ($ binaryPublicKey ),
194+ 'privateKey ' => base64_encode ($ binaryPrivateKey )
176195 ];
177196 }
178197}
0 commit comments