web-token / jwt-framework

JWT Framework
MIT License
889 stars 105 forks source link

openssl_sign(): supplied key param cannot be coerced into a private key #345

Closed b1tw0rker closed 2 years ago

b1tw0rker commented 2 years ago

Trying to Build a web-token jwt brings up the foloowing error:

openssl_sign(): supplied key param cannot be coerced into a private key.

Thats my code:

$vapidPublicKey = 'some87characterVAPIDKEYsstring'; $vapidPrivateKey = 'some43characterVAPIDKEYString';

$length = strlen($vapidPublicKey); $x = mb_substr($vapidPublicKey, 0, $length / 2); $y = mb_substr($vapidPublicKey, $length / 2, null);

use Base64Url\Base64Url; use Jose\Component\Core\AlgorithmManager; use Jose\Component\Core\JWK; use Jose\Component\Signature\Algorithm\ES256; use Jose\Component\Signature\JWSBuilder; use Jose\Component\Signature\Serializer\CompactSerializer;

// The algorithm manager with the HS256 algorithm. $algorithmManager = new AlgorithmManager([ new ES256(), ]);

$header = [ 'typ' => 'JWT', 'alg' => 'ES256', ];

$jwtPayload = json_encode([ 'sub' => 'https://www.host-x.de', 'exp' => time() + 3600, 'aud' => 'https://www.host-xd.de', ], JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);

// Our key. $jwk = new JWK([ 'kty' => 'EC', 'crv' => 'P-256', 'x' => Base64Url::encode($x), 'y' => Base64Url::encode($y), 'd' => Base64Url::encode($vapidPrivateKey), ]);

$jwsCompactSerializer = new CompactSerializer(); $jwsBuilder = new JWSBuilder(new AlgorithmManager([new ES256()])); $jws = $jwsBuilder ->create() ->withPayload($jwtPayload) ->addSignature($jwk, $header) ->build();

$jwt = $jwsCompactSerializer->serialize($jws, 0);

echo $jws;

What is going wring ? In MiniShlink/web-push the identic code is working fine.

Spomky commented 2 years ago

Hi,

The $vapidPublicKey should start with a \x04 character you have to remove. The lengths of 87 and 43 characters are strange. The keys shall be binary data, no base64 encoding. See this function for a working example.

Beside that, may I suggest you to use Spomky-Labs/web-push? This is the library I developed as I encountered lot of frictions and outdated code in the one from Minishlink.

With the library I created, you can easily use the keys with the format you provided. See https://web-push.spomky-labs.com/the-library/advanced-service#vapid-extension for details.

stale[bot] commented 2 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

github-actions[bot] commented 8 months ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.