Generate FFmpeg HLS Encryption Key and Key Info File

Securing HTTP Live Streaming (HLS) content is crucial for protecting video assets from unauthorized access and distribution. This guide provides a straightforward, step-by-step tutorial on how to generate an AES-128 encryption key and the corresponding key info file required by FFmpeg to encrypt HLS streams during the segmenting process.


Step 1: Generate the AES-128 Encryption Key

FFmpeg uses an AES-128 key to encrypt the HLS video segments. You need to generate a 16-byte (128-bit) binary key file using OpenSSL.

Run the following command in your terminal to generate a random 16-byte key and save it to a file named video.key:

openssl rand 16 > video.key

Step 2: Generate an Initialization Vector (Optional)

An Initialization Vector (IV) adds an extra layer of security. While FFmpeg can automatically use the segment sequence number as the IV if you leave this step out, generating a constant IV is common practice.

To generate a 32-character hexadecimal IV, run:

openssl rand -hex 16

Keep the output of this command (for example, d3b07384d113edec49eaa6238ad5ff00) to use in the key info file.

Step 3: Create the Key Info File

The key info file is a plain text file that tells FFmpeg where to find the encryption key, how the player should retrieve it, and what IV to use.

Create a new text file named video.keyinfo and format it exactly as follows, containing three lines:

https://yourserver.com/keys/video.key
video.key
d3b07384d113edec49eaa6238ad5ff00

Key Info File Breakdown:

Step 4: Run FFmpeg to Encrypt Your HLS Stream

Now that you have the encryption key and the key info file, you can instruct FFmpeg to encrypt your video. Use the -hls_key_info_file flag to pass the key info file.

Run the following FFmpeg command:

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

This command segments your input.mp4 file into encrypted 10-second TS segments, references the encryption key in the playlist.m3u8 playlist, and outputs the protected HLS stream.