Generate HLS Encryption Keys for FFmpeg

Securing HTTP Live Streaming (HLS) content requires encrypting video segments with AES-128 encryption so that only authorized clients can access the playback stream. This guide explains how to generate the 16-byte binary encryption key using OpenSSL, configure the key info file required by FFmpeg, and apply these assets to produce an encrypted HLS playlist.

1. Generate the AES-128 Encryption Key

HLS uses 128-bit (16-byte) symmetric keys to encrypt video segments. Generate this key in binary format using OpenSSL:

openssl rand 16 > stream.key

This command creates a raw 16-byte file named stream.key. Keep this file secure, as anyone with access to it can decrypt the video.

2. Generate an Initialization Vector (Optional)

An Initialization Vector (IV) provides additional cryptographic randomness. While FFmpeg can automatically generate sequence-based IVs, you can define a static 128-bit hex string manually:

openssl rand -hex 16

Copy the 32-character hexadecimal output for use in the key info file.

3. Create the Key Info File

FFmpeg uses a key info file to determine where to find the key locally, what URL to write inside the .m3u8 manifest for clients, and which IV to use.

Create a plain text file named stream.keyinfo with the following structure:

https://example.com/keys/stream.key
stream.key
0123456789abcdef0123456789abcdef

The file format consists of three lines:

  • Line 1 (Key URI): The remote URL or relative path where the video player will download the key during playback.
  • Line 2 (Local Path): The local path where FFmpeg can read the binary key file during encoding.
  • Line 3 (IV - Optional): The 32-character hex-encoded IV generated in step 2. If omitted, FFmpeg uses the segment sequence number as the IV.

4. Transcode and Encrypt with FFmpeg

Pass the stream.keyinfo file to FFmpeg using the -hls_key_info_file flag:

ffmpeg -i input.mp4 \
  -c:v libx264 -c:a aac \
  -hls_time 10 \
  -hls_playlist_type vod \
  -hls_key_info_file stream.keyinfo \
  playlist.m3u8

5. Verify the Encrypted Playlist

Inspect the generated playlist.m3u8 file. It should contain an #EXT-X-KEY tag preceding the segment list:

#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:10
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-KEY:METHOD=AES-128,URI="https://example.com/keys/stream.key",IV=0x0123456789abcdef0123456789abcdef
#EXTINF:10.000000,
playlist0.ts

When deployed to production, host stream.key behind an authentication mechanism to restrict playback access to authorized users.