Skip to content

Instantly share code, notes, and snippets.

@Spomky
Last active March 11, 2020 07:30
Show Gist options
  • Save Spomky/246eca6aaeeb7a40f11d3a2d98960282 to your computer and use it in GitHub Desktop.
Save Spomky/246eca6aaeeb7a40f11d3a2d98960282 to your computer and use it in GitHub Desktop.
Generate JWT for Apple Push Notification
<?php
require_once 'vendor/autoload.php';
use Jose\Factory\JWKFactory;
use Jose\Factory\JWSFactory;
$key_file = '/PATH/TO/KEY/FILE';
$secret = null; // If the key is encrypted, the secret must be set in this variable
$private_key = JWKFactory::createFromKeyFile($key_file, $secret, [
'kid' => 'ABC123DEFG', // The Key ID obtained from your developer account
'alg' => 'ES256', // Not mandatory but recommended
'use' => 'sig', // Not mandatory but recommended
]);
var_dump('We show our private EC key');
var_dump(json_encode($private_key));
var_dump('We prepare the payload (claims to sign).');
$payload = [
'iss' => 'DEF123GHIJ',
'iat' => time(),
];
var_dump($payload);
var_dump('We prepare the protected header.');
$header = [
'alg' => 'ES256',
'kid' => $private_key->get('kid'),
];
var_dump($header);
var_dump('We create our JWS using the private key, the payload and the header');
$jws = JWSFactory::createJWSToCompactJSON(
$payload,
$private_key,
$header
);
var_dump('We show our JWS.');
var_dump($jws);
/***************************************/
/* Same code as above without comments */
/***************************************/
$key_file = '/PATH/TO/KEY/FILE';
$secret = null;
$private_key = JWKFactory::createFromKeyFile($key_file, $secret, ['kid' => 'ABC123DEFG', alg' => 'ES256', 'use' => 'sig']);
$payload = ['iss' => 'DEF123GHIJ', 'iat' => time()];
$header = ['alg' => 'ES256', 'kid' => $private_key->get('kid')];
$jws = JWSFactory::createJWSToCompactJSON($payload, $private_key, $header);
@iisdan
Copy link

iisdan commented May 2, 2017

I am having the error "Unable to load the key" using a .p8 file

@hissain
Copy link

hissain commented Mar 11, 2020

I have a valid certificate cert.p12 exported from Mac Keychain. How can I know private and public key for alg ES256?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment