Skip to content

20: Authenticate TLS Streams with External PSKs

Use an external pre-shared key on a loopback connection. The client presents an identity and the server uses it to select the key.

  • PHP 8.6 CLI. Confirm the version with php --version.
  • The openssl extension with TLS 1.3, proc_open(), and access to loopback sockets.
  • Review the previous chapter if you’re following the series in order.

Allow about 15 minutes for the walkthrough and exercise.

A runnable tls-pre-shared-keys.php example. This example calls the shared loopback TLS lab.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/20-tls-pre-shared-keys/tls-pre-shared-keys.php
tls-pre-shared-keys.php
<?php
declare(strict_types=1);
require __DIR__ . '/../support/tls-lab.php';
runTlsLab('psk');
PSK handshake succeeded

PHP wraps each side’s key material in OpenSSL\Psk. The server returns null for unknown identities. This example generates an ephemeral 32-byte secret and shares it through a child-process pipe. Real peers need secure provisioning and scoped identities.

In the lab’s PSK branch, psk_client_cb returns the key alongside the identity tutorial-client. The server’s psk_server_cb receives that identity and supplies the corresponding key. The lab uses PSK authentication for this connection, so the server needs no certificate.

Change the client identity to unknown in the lab helper’s PSK branch and observe the handshake fail. Change it back to tutorial-client to restore the connection.

Continue with Send TLS 1.3 Early Data.