Skip to content

Instantly share code, notes, and snippets.

@Spomky Spomky/apn.php
Last active Jun 10, 2018

Embed
What would you like to do?
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);
@edamov

This comment has been minimized.

Copy link

commented Oct 10, 2016

I have one more question. I already have a file (.p8) from APNS with private key in format:

-----BEGIN PRIVATE KEY-----
<HERE_IS_A_VERY_LONG_KEY>
-----END PRIVATE KEY-----

How I should use it with this example?

@edamov

This comment has been minimized.

Copy link

commented Oct 10, 2016

So I tried to create a private key in such way:

$certificate = 'PATH_TO_CERTIFICATE';
$private_key = JWKFactory::createFromCertificate(file_get_contents($certificate));
// OR
$private_key = JWKFactory::createFromCertificateFile($certificate);

But in both cases I have an error:
Warning: openssl_x509_read(): supplied parameter cannot be coerced into an X509 certificate! at vendor/spomky-labs/jose/src/KeyConverter/KeyConverter.php line 50

@Spomky

This comment has been minimized.

Copy link
Owner Author

commented Oct 10, 2016

The methods createFromCertificate* should be used with X509 certificates.
The file you have is not a certificate, but just a key encoded in PEM. The method to use is createFromKeyFile.

$key_file = 'PATH_TO_FILE';
$private_key = JWKFactory::createFromKeyFile($key_file, 'YOUR PASSWORD IF THE KEY IS ENCRYPTED. ELSE NULL', [
    'kid' => 'ABC123DEFG', // The Key ID obtained from your developer account
    'alg' => 'ES256',      // Not mandatory but recommended
    'use' => 'sig',        // Not mandatory but recommended
]);
@Spomky

This comment has been minimized.

Copy link
Owner Author

commented Oct 10, 2016

The Gist is now up to date.

Compact code on last lines (https://gist.github.com/Spomky/246eca6aaeeb7a40f11d3a2d98960282#file-apn-php-L50:L55)

@Spomky

This comment has been minimized.

Copy link
Owner Author

commented Oct 10, 2016

I noted you also opened an issue on namshi/jose library.
In case you missed it, the ES256 algorithm of this library still produces wrong signatures (see namshi/jose#94 and namshi/jose#98).

A PR exists, but it is not yet merged.

@edamov

This comment has been minimized.

Copy link

commented Oct 11, 2016

Great thanks!
But now I have an error Unable to load the key in loadKeyFromPEM() method, because both openssl_pkey_get_private() and openssl_pkey_get_public() returns false with my key and I don't know what is wrong with my key.
Can you give any suggestion?

@Spomky

This comment has been minimized.

Copy link
Owner Author

commented Oct 15, 2016

Is it password protected?

If it is possible to generate a new one, could you please send it to me?
I will try to find out where the error comes from.

@edamov

This comment has been minimized.

Copy link

commented Oct 17, 2016

It is not password protected.
I've resolved the previous issue with updating php openssl extension to version 1.0.2j (before I have 1.0.1f and it didn't work).
But I still have an error Unable to load the key in Jose\KeyConverter\ECKey->loadPEM() function.

Here is my p8 key:

-----BEGIN PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQg13n3isfsEktzl+CtH5ECpRrKk+40prVuCbldkP77gamgCgYIKoZIzj0DAQehRANCAARhwgxSRqXBt54BWRQXoU/doFWULOWrER3uLS43/iugDW1PMDliQZEzWetYAdf+Mafq/PrlbEAfA+l7JfmijAsv
-----END PRIVATE KEY-----
@Spomky

This comment has been minimized.

Copy link
Owner Author

commented Oct 17, 2016

Many thanks.

I think I have found the error. It seems it comes from my library which is not fully compliant with the RFC5915

In the Elliptic Curve Private Key Format, the parameters are optional, however my library reject private keys without parameters.
I will try to push a fix today.

Stay tuned.

@Spomky

This comment has been minimized.

Copy link
Owner Author

commented Oct 17, 2016

Do you allow me to use this key in a new test case for the library?

@edamov

This comment has been minimized.

Copy link

commented Oct 17, 2016

Yes, I do =)

@smccoy78

This comment has been minimized.

Copy link

commented Mar 9, 2017

Has a solution to the issue @edamov listed above been found? I am getting a similar "Unable to load the key" error. I'm not sure if my issue starts like @edamov's did with the openssl needing to be upgraded or not. Any ideas?

  1. in Assertion.php line 275
  2. at Assertion::createException(true, 'Unable to load the key', '38', null) in Assertion.php line 1644
  3. at Assertion::false(true, 'Unable to load the key') in KeyConverter.php line 157
  4. at KeyConverter::loadKeyFromPEM('-----BEGIN PRIVATE KEY----- private key -----END PRIVATE KEY-----', null) in KeyConverter.php line 120
  5. at KeyConverter::loadFromKey('-----BEGIN PRIVATE KEY----- private key -----END PRIVATE KEY-----', null) in KeyConverter.php line 104
  6. at KeyConverter::loadFromKeyFile('APNsAuthKey.p8', null) in JWKFactory.php line 161
  7. at JWKFactory::createFromKeyFile('APNsAuthKey.p8', null, array('kid' => 'key_id', 'alg' => 'ES256', 'use' => 'sig')) in ApiSupportController.php line 330
@iisdan

This comment has been minimized.

Copy link

commented May 2, 2017

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.