Stream Encrypted Files Over HTTP Using FFmpeg
Streaming encrypted media over HTTP secures your content from unauthorized downloads and ensures safe transit. This article provides a step-by-step guide on how to encrypt video files using AES-128 encryption and package them for HTTP Live Streaming (HLS) using FFmpeg.
Step 1: Create the Encryption Key and Key Info File
To encrypt your stream, you need a 16-byte AES encryption key and a key info file that tells FFmpeg how to apply it.
Generate a random 16-byte key using OpenSSL:
openssl rand 16 > video.keyGenerate a random Initialization Vector (IV) (optional, but recommended for security):
openssl rand -hex 16 > video.ivCreate a key info file named
key_info.txt. This file must contain three lines:- Line 1: The URI where the player will retrieve the key over HTTP (use HTTPS in production).
- Line 2: The local path to the key file on your disk.
- Line 3: The IV (hexadecimal string) generated in the previous step.
Example of
key_info.txt:https://example.com/keys/video.key /path/to/video.key e84a2f8b9c1d0e3f4a5b6c7d8e9f0a1b
Step 2: Encrypt and Segment the Video with FFmpeg
Use FFmpeg to convert your input video file into encrypted HLS
segments (.ts files) and generate the playlist
(.m3u8) file. Run the following command in your
terminal:
ffmpeg -i input.mp4 \
-codec:v libx264 -codec:a aac \
-hls_time 10 \
-hls_key_info_file key_info.txt \
-hls_playlist_type vod \
-hls_segment_filename "segment_%03d.ts" \
playlist.m3u8Command breakdown: * -i input.mp4:
Specifies the input video. * -codec:v libx264 -codec:a aac:
Encodes video to H264 and audio to AAC (standard for HLS). *
-hls_time 10: Sets the target segment duration to 10
seconds. * -hls_key_info_file key_info.txt: Tells FFmpeg to
encrypt the segments using the details in your key info file. *
-hls_playlist_type vod: Creates a Video-on-Demand playlist.
* playlist.m3u8: The output playlist file.
Step 3: Stream and Serve the Encrypted Files
To stream the video to clients over HTTP, upload the generated
.ts segments, the playlist.m3u8 file, and the
video.key file to your web server.
When an HLS-compatible player (like Video.js, hls.js, or native
Safari) loads playlist.m3u8: 1. It reads the playlist and
finds the URL of the key. 2. It makes an HTTP request to retrieve
video.key. 3. It downloads the encrypted .ts
segments. 4. It decrypts the segments locally in memory using the key
and plays the video.
Best Practices for HTTP Key Protection
Because the video key is requested over HTTP, you must secure the key
endpoint: * Use HTTPS: Always serve the key and the
stream over HTTPS to prevent man-in-the-middle interception. *
Implement Authentication: Configure your web server to
require token authentication, session cookies, or referrer validation
before serving the video.key file. This ensures only
authorized users can decrypt the stream.