'Trouble serializing payload with ES256 with JWS

Here is my current code.

use Jose\Component\Core\AlgorithmManager;
use Jose\Component\Core\JWK;
use Jose\Component\Signature\Algorithm\ES256;
use Jose\Component\Signature\JWSBuilder;
$algorithm_manager = new AlgorithmManager([
    new ES256(),
]);
$header = array("zip" => "DEF","alg" => "ES256","kid" => "...kid...");
$payload = array("info...");
$js = json_encode($payload,JSON_UNESCAPED_SLASHES);
$jwk = new JWK([
    'kty' => 'ES256',
    'k' => '...kid...',
]);
$jwsBuilder = new JWSBuilder($algorithm_manager);
$jws = $jwsBuilder
    ->create()                               // We want to create a new JWS
    ->withPayload($js)                  // We set the payload
    ->addSignature($jwk, ['alg' => 'ES256']) // We add a signature with a simple protected header
    ->build(); 

$serializer = new CompactSerializer(); // The serializer

$token = $serializer->serialize($jws, 0); // We serialize the signature at index 0 (we only have one signature).

Whenever I try to serialize this it tells me this error.

Fatal error: Uncaught InvalidArgumentException: Wrong key type. in vendor/web-token/jwt-framework/src/SignatureAlgorithm/ECDSA/ECDSA.php:72

This is the first time i'm using this software so i may be forgetting a step or something.

Would some one be so kind as to point me to where im going wrong?



Solution 1:[1]

Couple of notes

  1. ES256 is an asymmetric algorithm that requires an EC (elliptic curve) P-256 curve (crv) key. You're currently passing, well, for a lack of better word - nonsense - k in JWK is "Key Value" of a symmetric ("kty":"oct") secret.

  2. "zip": "DEF" is a JWE header that has no place or use in a JWS.

For 1) pass a private P-256 EC key, for 2) get rid of this header.

An example P-256 private key in JWK format looks like this

{
  kty: 'EC',
  x: 'WoOQG8MYKVOUIOj3Ps1r_2qpQyPIef9MC9due2kJJZU',
  y: 'uLci-1X5VlGCo9-Pei7fBk5W9R8Gw8nEUHoUmf-tJIg',
  crv: 'P-256',
  d: 'Ma-sIY1NsqaISoDUyCTDp2PMuuA42Yb3I2Wcp4QLRDE'
}

It's public JWK form (for verification) is

{
  kty: 'EC',
  x: 'WoOQG8MYKVOUIOj3Ps1r_2qpQyPIef9MC9due2kJJZU',
  y: 'uLci-1X5VlGCo9-Pei7fBk5W9R8Gw8nEUHoUmf-tJIg',
  crv: 'P-256'
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Filip Skokan