How to Encrypt HLS Segments with AES-128 Using FFmpeg

This article provides a straightforward, step-by-step guide on how to secure HTTP Live Streaming (HLS) video streams by encrypting their media segments with AES-128 encryption using FFmpeg. You will learn how to generate an encryption key, construct the required key info file, and execute the FFmpeg command to output a fully encrypted HLS playlist.

Step 1: Generate the AES-128 Encryption Key

AES-128 requires a 16-byte (128-bit) encryption key. You can generate a random key file using OpenSSL in your terminal:

openssl rand 16 > enc.key

This command creates a binary file named enc.key containing the 16-byte key.

(Optional) You can also generate a random Initialization Vector (IV) to increase security, though FFmpeg will use the segment sequence number as the IV by default if you do not provide one:

openssl rand -hex 16

Step 2: Create the Key Info File

FFmpeg requires a format-specific “key info” file to locate the encryption key and write the correct metadata into the HLS playlist (.m3u8). Create a plain text file named enc.keyinfo with exactly three lines (or two, if omitting the IV):

https://yourserver.com/path/to/enc.key
enc.key
00112233445566778899aabbccddeeff

Step 3: Run the FFmpeg Encryption Command

With your source video, the encryption key, and the key info file ready in the same directory, run the following FFmpeg command to segment and encrypt your video:

ffmpeg -i input.mp4 \
  -c:v libx264 -c:a aac \
  -hls_time 10 \
  -hls_key_info_file enc.keyinfo \
  -hls_playlist_type vod \
  -hls_segment_filename "segment_%03d.ts" \
  output.m3u8

Parameter Breakdown:

Once the process finishes, the output .m3u8 file will contain the #EXT-X-KEY tag pointing to your key URL, and the .ts video segments will be fully encrypted with AES-128.