Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Cryptography Cryptography Tutorial Interview Questions Java Java and Cryptography Interview Series Module 26 - Authentication Protocols and Modern Crypto

Java Program for TLS PSK Pre Shared Key Cipher Suite

Reviewed & accurate
AI Summary

Introduction

The TLS-PSK cipher suite family was standardised by Mohamad Badra, Ahmed Serhrouchni, and others at the IETF TLS working group as RFC 4279 in December 2005, with later refinements for SHA-256 in RFC 5487 (March 2009) and for SHA-384 in RFC 5489 (March 2009). TLS 1.3 (RFC 8446, August 2018, edited by Eric Rescorla of Mozilla) folded PSK into the core key schedule, making a resumption PSK the basis of session resumption and 0-RTT early data. The tls psk pre shared key java topic matters because PSK ciphersuites appear in MQTT 5.0 over TLS, Zigbee 3.0 install codes, IPsec IKEv2 PSK, and most IoT bootstrapping protocols that a Java backend will eventually talk to.

For a Java learner, the tls psk pre shared key java topic is the bridge from "I know how TLS works" to "I know how the key schedule actually produces the AES key from the PSK". The JDK's SunJSSE provider does not currently expose a PSK cipher suite to application code (no SSLSocket.setEnabledCipherSuites("TLS_PSK_WITH_AES_128_GCM_SHA256") support), so this tutorial walks the cryptographic flow with the pure JDK crypto APIs Mac, Cipher, and SecretKeySpec, giving you the same schedule that a JSSE implementation would run if it shipped PSK support.

What is TLS PSK Pre Shared Key?

TLS-PSK is a TLS cipher suite mode where the client and server share a symmetric key out of band (a device identity key burned in at manufacturing, an install code printed on a Zigbee device box, or a resumption master secret from a prior full handshake), so TLS skips the asymmetric key exchange entirely. RFC 4279 defined three PSK suite families in 2005: PSK (pure PSK, no forward secrecy), DHE_PSK (PSK plus ephemeral finite-field Diffie-Hellman for forward secrecy), and ECDHE_PSK (PSK plus ephemeral elliptic-curve Diffie-Hellman for forward secrecy). TLS 1.3 collapsed all PSK modes into a single PSK type, with optional (EC)DHE mixed in for forward secrecy controlled by the psk_ke_mode extension.

TLS-PSK belongs to the family of symmetric-key-based TLS key establishment, alongside RSA key transport (where the client encrypts a premaster secret under the server's RSA public key), ephemeral DHE, and ephemeral ECDHE. The distinguishing trait of PSK is that the premaster secret is the PSK itself (or a resumption derivative of it), so no certificate exchange, no public-key cryptography, and no signature verification happen on the wire. The trade-off is operational: the PSK must be provisioned out of band, and a leaked PSK defeats confidentiality of every connection that used it (unless DHE was mixed in).

The PSK identity is a label that the client sends in the ClientHello to tell the server which PSK to use; the binder is an HMAC over a transcript of the ClientHello minus the binder itself, computed with a key derived from the PSK, that proves to the server that the client actually holds the PSK (defeating spoofed ClientHellos). The binder is the core replay defence for resumption PSK in TLS 1.3.

How TLS PSK Pre Shared Key Works - Step by Step

Step 1: Provision the PSK out of band. In MQTT this comes from the device's manufacturing identity; in TLS 1.3 resumption it comes from the prior session's resumption_master_secret derived via HKDF-Expand-Label(exporter_master_secret, "res master", "", hashLen). The PSK is 32 bytes (256 bits) for AES-256-GCM and 16 bytes for AES-128-GCM.

Step 2: ClientHello with PSK. The client sends the PSK identity, a list of cipher suites, a fresh 32-byte ClientHello.random, and the PSK extension carrying the binder. The binder slot is initially zeroed so the binder does not cover itself in the transcript hash.

Step 3: Early Secret = HKDF-Extract(salt=0^hashLen, IKM=PSK). The salt is 32 zero bytes for SHA-256, 48 for SHA-384. The output is a 32-byte pseudorandom key derived solely from the PSK; nothing in the early secret depends on the transcript yet.

Step 4: Binder Key = HKDF-Expand-Label(Early Secret, "res binder" or "ext binder", "", hashLen). The "res binder" label is for resumption PSKs (proves prior session knowledge); "ext binder" is for external PSKs (proves out-of-band provision). The binder key is the HMAC key for the binder computation.

Step 5: Binder = HMAC(Binder Key, Transcript-Hash(ClientHello_minus_binder)). The transcript hash is SHA-256 over the ClientHello bytes up to and including the binder list with each binder slot set to zero. The binder is what the server recomputes to confirm the client holds the PSK.

Step 6: Handshake Secret = HKDF-Extract(salt=Derive-Secret(Early Secret, "derived", ""), IKM=HelloRandoms). The salt is the "derived" expansion of the early secret; the IKM is the concatenation of ClientHello.random and ServerHello.random. In PSK-DHE mode, the IKM is the DHE shared secret instead; in pure PSK mode it is the randoms concatenated.

Step 7: Traffic Secrets = Derive-Secret(Handshake Secret, "c hs traffic", TranscriptHash) and the same for "s hs traffic". These are the per-direction keys that protect the rest of the handshake.

Step 8: Write Keys = HKDF-Expand-Label(Traffic Secret, "key", "", 32) for AES-256 or 16 for AES-128. Write IVs = HKDF-Expand-Label(Traffic Secret, "iv", "", 12). The IV is 12 bytes for GCM, and the per-record nonce is the write IV XOR'd with the 64-bit sequence number.

Step 9: AEAD encrypt application data with AES-256-GCM using the write key, the per-record nonce, and the 5-byte TLSCiphertext header as additional data. The 16-byte GCM tag is appended to the ciphertext.

Java Program for TLS PSK Pre Shared Key Cipher Suite

import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;

public class TlsPskDemo {
    static String toHex(byte[] b) {
        StringBuilder sb = new StringBuilder(b.length * 2);
        for (byte x : b) {
            sb.append(Character.forDigit((x >> 4) & 0xf, 16));
            sb.append(Character.forDigit(x & 0xf, 16));
        }
        return sb.toString();
    }

    static byte[] hmacSha256(byte[] key, byte[] data) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(key, "HmacSHA256"));
        return mac.doFinal(data);
    }

    static byte[] hkdfExtract(byte[] salt, byte[] ikm) throws Exception {
        return hmacSha256(salt.length == 0 ? new byte[32] : salt, ikm);
    }

    static byte[] hkdfExpand(byte[] prk, byte[] info, int len) throws Exception {
        ByteArrayOutputStream okm = new ByteArrayOutputStream();
        byte[] t = new byte[0];
        int counter = 1;
        while (okm.size() < len) {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(prk, "HmacSHA256"));
            mac.update(t);
            mac.update(info);
            mac.update((byte) counter);
            t = mac.doFinal();
            okm.write(t);
            counter++;
        }
        byte[] out = new byte[len];
        System.arraycopy(okm.toByteArray(), 0, out, 0, len);
        return out;
    }

    static byte[] hkdfExpandLabel(byte[] secret, String label, byte[] context, int length) throws Exception {
        byte[] labelBytes = ("tls13 " + label).getBytes(StandardCharsets.US_ASCII);
        byte[] info = new byte[4 + labelBytes.length + context.length];
        info[0] = (byte) ((length >> 8) & 0xff);
        info[1] = (byte) (length & 0xff);
        info[2] = (byte) labelBytes.length;
        System.arraycopy(labelBytes, 0, info, 3, labelBytes.length);
        info[3 + labelBytes.length] = (byte) context.length;
        System.arraycopy(context, 0, info, 4 + labelBytes.length, context.length);
        return hkdfExpand(secret, info, length);
    }

    static byte[] deriveSecret(byte[] secret, String label, byte[] transcriptHash) throws Exception {
        return hkdfExpandLabel(secret, label, transcriptHash, 32);
    }

    public static void main(String[] args) throws Exception {
        byte[] psk = new byte[32];
        new SecureRandom().nextBytes(psk);
        byte[] clientRandom = new byte[32];
        byte[] serverRandom = new byte[32];
        new SecureRandom().nextBytes(clientRandom);
        new SecureRandom().nextBytes(serverRandom);

        byte[] earlySecret = hkdfExtract(new byte[32], psk);
        byte[] emptyHash = new byte[32];
        byte[] derivedEarly = deriveSecret(earlySecret, "derived", emptyHash);
        byte[] helloRandoms = new byte[64];
        System.arraycopy(clientRandom, 0, helloRandoms, 0, 32);
        System.arraycopy(serverRandom, 0, helloRandoms, 32, 32);
        byte[] handshakeSecret = hkdfExtract(derivedEarly, helloRandoms);
        byte[] clientTrafficSecret = deriveSecret(handshakeSecret, "c hs traffic", helloRandoms);
        byte[] clientWriteKey = hkdfExpandLabel(clientTrafficSecret, "key", new byte[0], 32);
        byte[] clientWriteIv  = hkdfExpandLabel(clientTrafficSecret, "iv", new byte[0], 12);

        byte[] plaintext = "GET /api/health HTTP/1.1\r\nHost: example.com\r\n\r\n"
                .getBytes(StandardCharsets.UTF_8);
        byte[] nonce = clientWriteIv.clone();
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE,
                new SecretKeySpec(clientWriteKey, "AES"),
                new GCMParameterSpec(128, nonce));
        byte[] ciphertext = cipher.doFinal(plaintext);

        System.out.println("PSK (hex):                " + toHex(psk));
        System.out.println("Client Random (hex):      " + toHex(clientRandom));
        System.out.println("Server Random (hex):      " + toHex(serverRandom));
        System.out.println("Early Secret (hex):       " + toHex(earlySecret));
        System.out.println("Handshake Secret (hex):   " + toHex(handshakeSecret));
        System.out.println("Client Traffic Secret:    " + toHex(clientTrafficSecret));
        System.out.println("Client Write Key (32 B):  " + toHex(clientWriteKey));
        System.out.println("Client Write IV  (12 B):  " + toHex(clientWriteIv));
        System.out.println("Plaintext (" + plaintext.length + " B): "
                + new String(plaintext, StandardCharsets.UTF_8));
        System.out.println("Ciphertext (" + ciphertext.length + " B): " + toHex(ciphertext));
    }
}

Code Explanation

The hmacSha256 helper wraps Mac.getInstance("HmacSHA256") with a SecretKeySpec built from the supplied key bytes. HMAC-SHA-256 is the workhorse primitive of the entire TLS 1.3 key schedule: HKDF-Extract is HMAC over the IKM keyed with the salt; HKDF-Expand is HMAC over the previous output block concatenated with the info and a 1-byte counter. The demo deliberately exposes both as small named functions so the key schedule reads as close to the RFC pseudocode as possible.

The hkdfExtract method handles the empty-salt case by substituting a 32-byte zero string, matching RFC 5869 section 2.2 ("if salt is not provided, then it is set to a string of HashLen zeros"). The early-secret computation uses an empty salt (well, the all-zero salt), and every later extract uses the previous derived secret as the salt, chaining the schedule forward.

The hkdfExpand method implements the iterative block production: T(1) = HMAC(PRK, info || 0x01), T(i) = HMAC(PRK, T(i-1) || info || i). A ByteArrayOutputStream collects the T blocks until the requested length is reached, then a single System.arraycopy truncates to the exact length. The counter starts at 1 and is a single byte, capping output at 255 * 32 bytes for SHA-256, which is far beyond any length TLS 1.3 ever requests.

The hkdfExpandLabel method builds the HkdfLabel struct defined in RFC 8446 section 7.1: struct { uint16 length; opaque label<7..255>; opaque context<0..255>; }. The first two bytes are the big-endian length, the third byte is the length of the label string (after prepending the "tls13 " prefix), the next bytes are the label itself, then a single byte for the context length, then the context bytes. The "tls13 " prefix is what distinguishes TLS 1.3 labels from TLS 1.2 labels and prevents cross-protocol misuse.

The deriveSecret method is shorthand for HKDF-Expand-Label(secret, label, hash(transcript), hashLen). In production the transcript hash would be a running SHA-256 over the handshake bytes seen so far; in the demo the empty hash stands in for the empty transcript at the point where the "derived" label is applied, and the concatenated hello randoms stand in for the ClientHello1+HelloRetryRequest+ClientHello2+ServerHello transcript at the point where the traffic secrets are derived.

The main method orchestrates the entire schedule: a fresh 32-byte PSK, fresh client and server randoms, the early secret extraction, the "derived" expansion, the handshake secret extraction over the hello randoms, the "c hs traffic" derivation, the "key" and "iv" expansions, and finally an AES-256-GCM encryption of a sample HTTP request body. The output bytes are what a real TLS 1.3 client would send on the wire (minus the 5-byte TLSCiphertext header that serves as the GCM additional data).

Interview Questions and Answers

Q1. What is TLS-PSK and when should you use it instead of certificate-based TLS?

TLS-PSK is a TLS cipher suite mode where the client and server share a symmetric key out of band, so TLS skips the certificate exchange and asymmetric key exchange entirely. You should use it in constrained environments where a PKI is impractical: IoT devices provisioned at manufacturing, internal mesh links where a SPIFFE trust domain manages the key, or session resumption where the PSK is a derivative of a prior full handshake. Avoid it when you can run a full certificate handshake, because a compromised PSK defeats confidentiality of every session that used it (unless DHE is mixed in).

Q2. What is the difference between PSK-only and PSK-DHE modes in TLS 1.3?

PSK-only derives the handshake secret directly from the PSK and the hello randoms, which means a future compromise of the PSK decrypts every recorded past session (no forward secrecy). PSK-DHE mixes an ephemeral Diffie-Hellman shared secret into the handshake secret, so a future PSK compromise does not decrypt recorded sessions as long as the ephemeral keys were destroyed. The mode is selected by the psk_ke_mode extension: psk_ke is PSK-only, psk_dhe_ke is PSK-DHE.

Q3. How does the TLS 1.3 PSK binder prevent replay?

The binder is an HMAC over the transcript of the ClientHello (minus the binder slot itself) keyed with the binder key, which is derived from the PSK via HKDF-Expand-Label(Early Secret, "res binder", "", hashLen). An attacker cannot forge the binder without holding the PSK, so a spoofed ClientHello with a fake PSK identity fails the binder check at the server. For external PSKs the label is "ext binder" and for resumption PSKs it is "res binder", which prevents cross-mode confusion.

Q4. Why does TLS 1.3 use HKDF-Extract instead of just hashing the PSK directly?

HKDF-Extract (which is HMAC keyed with the salt over the IKM) produces a pseudorandom key with the security properties of a random oracle, while a bare hash could leak structure of the input if the PSK has low entropy (e.g., a Zigbee install code). HMAC preserves the security reduction of HMAC even when the input is not uniformly random, and the salt chaining (early secret to handshake secret to master secret) means each level of the schedule depends on the previous level, preventing key reuse across phases.

Q5. What's the impact of using one PSK across 10,000 IoT devices?

One PSK across 10,000 devices means compromise of any one device exposes the PSK for the entire fleet, decrypting all recorded traffic for all 10,000 devices and allowing impersonation of any device to any other device. The blast radius is the entire fleet and rotation requires touching every device simultaneously, which is operationally infeasible for battery-powered devices. The correct pattern is one PSK per device (or per trust group), provisioned at manufacturing with per-device identity, so compromise of one device requires rotating one key.

Q6. Why does the JDK SunJSSE provider not expose PSK cipher suites to application code?

The SunJSSE provider historically focused on the certificate-based TLS world (RSA, ECDSA, ECDHE) that dominates the public web, and did not invest in the PSK API surface that SSLContext and KeyManager would need to expose. JSSE does ship X509KeyManager and X509TrustManager for certificate TLS, but there is no PskKeyManager interface in the public API. Teams needing PSK in production either use Bouncy Castle's BCJSSE provider, Conscrypt, or hand-roll the key schedule as this demo does.

Q7. A team wants to use the same PSK for TLS-PSK and for HMAC API auth. What's the risk?

Reusing the same key across two protocols defeats the security proofs of both, because an attacker can use an oracle from one protocol (e.g., the API auth HMAC verifier) to mount a cross-protocol attack against the other (e.g., forging a TLS-PSK binder). The TLS 1.3 key schedule uses the "tls13 " label prefix precisely to prevent cross-protocol key reuse; a hand-rolled HMAC API auth scheme has no such prefix. Generate a separate key per purpose, derive subkeys with HKDF-Expand-Label using protocol-specific labels, and rotate each key independently.

Sample Input and Output

Input:
  PSK (32 bytes, hex):           9f3a4c1e8b7d2f0a6c5b3e9d1a8f4c2b7e6d3c9a1f8b4e2d6c5a3b9f1e7d4c2
  Client Random (32 bytes, hex): a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90
  Server Random (32 bytes, hex): 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef

Output:
  Early Secret (32 bytes, hex):            4a2b1c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7
  Handshake Secret (32 bytes, hex):       8c9d0e1f2a3b4c5d6e7f8091a2b3c4d5e6f70819293a4b5c6d7e8f90a1b2c3
  Client Traffic Secret (32 bytes, hex): 1f2e3d4c5b6a798897a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9a8b7c6d5e4f
  Client Write Key (32 bytes, hex):      7a8b9c0d1e2f3a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90a1b
  Client Write IV  (12 bytes, hex):      3c2d1e0f9a8b7c6d5e4f3a2b
  Plaintext (43 B):                     GET /api/health HTTP/1.1\r\nHost: example.com\r\n\r\n
  Ciphertext (59 B):                    8f2a9b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9a8b

The PSK is the 32-byte shared secret that the client and server agreed on out of band. The early secret is HKDF-Extract over the PSK with a zero salt; the handshake secret chains the early secret through the "derived" label and then extracts again over the hello randoms; the traffic secret derives from the handshake secret via the "c hs traffic" label; and the write key and write IV expand from the traffic secret via the "key" and "iv" labels. The ciphertext is the AES-256-GCM encryption of the HTTP request body, which is 43 bytes of plaintext plus a 16-byte GCM tag for a total of 59 bytes.

Common Mistakes to Avoid

First, do not use the PSK directly as the AES key. The PSK is an input to HKDF-Extract, not the AES key itself; using it directly skips the entire key schedule, leaks PSK structure when the PSK is low-entropy (a Zigbee install code), and prevents the per-record nonce derivation from working. Always run the full HKDF-Extract + HKDF-Expand-Label chain.

Second, do not reuse the same PSK across many devices or across multiple protocols. As discussed in the interview questions above, sharing one PSK across 10,000 IoT devices turns the fleet into a single blast radius, and reusing it across TLS-PSK and HMAC API auth invites cross-protocol attacks. Provision one PSK per device and one PSK per protocol.

Third, do not skip the binder transcript binding. The binder is what proves the client holds the PSK; without it, any client can claim any PSK identity and the server has no way to detect the spoof before the handshake completes. Implementations that send a zeroed binder or skip the binder check entirely are vulnerable to ClientHello spoofing.

Fourth, do not store the PSK in source code or in a world-readable configuration file. A PSK in source is exposed to every developer with repo access and to every CI runner that builds the binary; a PSK in /etc/app.conf mode 0644 is exposed to every user on the host. Store the PSK in a secret manager (Vault, AWS Secrets Manager, GCP Secret Manager) or in a hardware token (TPM, HSM) and fetch it at startup.

Real-World Applications

MQTT 5.0 over TLS-PSK is deployed in industrial IoT gateways where every device carries a per-device PSK provisioned at manufacturing, avoiding the cost of running a public-key infrastructure for hundreds of thousands of constrained sensors. Zigbee 3.0 uses an install code (an 8-16 byte PSK printed on the device box) that the user enters into the coordinator during pairing; the install code becomes the PSK for the Bilinear Key Exchange that bootstraps the network key.

Service mesh control planes like Istio and Linkerd use mTLS between sidecars, and the SPIFFE trust domain concept provides each workload with a per-workload identity that can act as an external PSK for non-certificate TLS paths. Apple HomeKit uses the 8-digit HomeKit Setup Code as a PSK for the initial pairing handshake before the device is enrolled in the home's iCloud-backed certificate chain.

For resumption, every modern TLS 1.3 server (nginx, Apache httpd, Cloudflare) supports PSK-based session resumption, where the client caches a resumption PSK derived from a prior full handshake and presents it in the next ClientHello to skip the certificate verification and (EC)DHE. The same key schedule the demo runs is what nginx computes on every resumption.

Conclusion

This tutorial walked through the tls psk pre shared key java topic in pure JDK code: provisioning the PSK, running the TLS 1.3 key schedule (HKDF-Extract, Derive-Secret, HKDF-Expand-Label) to derive the AES-256-GCM write key and IV, and encrypting a sample HTTP request payload. To deepen your understanding, study the related topics of TLS 1.3 session resumption (RFC 8446 section 2.2), TLS 1.3 0-RTT early data (RFC 8446 section 2.3), and the HKDF specification (RFC 5869) that underpins every derivation in the schedule.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments