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.keyThis 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 16Step 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
- Line 1: The URL where the HLS player will fetch the key file during playback.
- Line 2: The local path to the key file you generated in Step 1 (FFmpeg uses this to perform the actual encryption).
- Line 3 (Optional): The hexadecimal Initialization Vector (IV). If left blank, FFmpeg will use the segment sequence number.
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.m3u8Parameter Breakdown:
-hls_time 10: Sets the target duration for each segment to 10 seconds.-hls_key_info_file enc.keyinfo: Tells FFmpeg to encrypt the segments using the settings defined in your key info file.-hls_playlist_type vod: Creates a static video-on-demand playlist.output.m3u8: The final HLS index file that links to the encrypted.tssegments.
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.