HLS.js Guide and Best Practices
Master the core technology of HLS streaming media playback, including working principles, basic code examples, common configurations, event listening, and error handling.
Read More →Build a secure video distribution system to protect content copyright
HLS (HTTP Live Streaming) is currently one of the most widely used streaming media transmission protocols. In scenarios such as paid video, online education, and corporate training, content security is crucial. HLS provides a standardized encryption mechanism that can effectively prevent video content from being illegally downloaded and distributed.
HLS encryption mainly has two schemes: AES-128 full-segment encryption and SAMPLE-AES sample encryption. Both schemes have their own advantages and disadvantages, suitable for different security needs and performance requirements. This article will detail the principles, implementation steps, and best practices of these two encryption methods.
HLS encryption is based on symmetric encryption algorithms, encrypting media segments before transmission, with the player decrypting in real-time during playback. The entire process is transparent to users but can effectively protect content security.
HLS specifies the encryption method and key address through the EXT-X-KEY tag:
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:10
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-KEY:METHOD=AES-128,URI="https://example.com/key.key",IV=0x00000000000000000000000000000000
#EXTINF:10.0,
segment00000.ts
#EXTINF:10.0,
segment00001.ts
#EXT-X-ENDLIST
AES-128 is the most basic and best compatibility encryption method for HLS, encrypting the entire TS segment.
First, generate a 16-byte (128-bit) random key:
# Generate key using OpenSSL
openssl rand -out key.key 16
# View key (hexadecimal)
hexdump -e '16/1 "%02x" "\n"' key.key
Use FFmpeg to generate encrypted HLS streams:
ffmpeg -i input.mp4 \
-c:v libx264 -c:a aac \
-hls_time 10 \
-hls_key_info_file key_info.txt \
-hls_playlist_type vod \
-hls_segment_filename "segment%05d.ts" \
output.m3u8
The key_info.txt file format is as follows:
https://example.com/keys/key.key
key.key
0123456789abcdef0123456789abcdef
The first line is the URI address of the key, the second line is the local key file path, and the third line is the optional IV (initialization vector).
SAMPLE-AES is another HLS encryption method proposed by Apple, which encrypts only part of the media samples, reducing performance overhead while ensuring security.
ffmpeg -i input.mp4 \
-c:v libx264 -c:a aac \
-hls_time 10 \
-hls_key_info_file key_info.txt \
-hls_encryption_method sample-aes \
-hls_playlist_type vod \
output.m3u8
Key management is the most critical part of the HLS encryption system. Once the key is leaked, encryption loses its meaning.
Regularly changing keys can reduce the risk of key leakage:
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:10
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-KEY:METHOD=AES-128,URI="https://example.com/key1.key"
#EXTINF:10.0,
segment00000.ts
#EXTINF:10.0,
segment00001.ts
#EXT-X-KEY:METHOD=AES-128,URI="https://example.com/key2.key"
#EXTINF:10.0,
segment00002.ts
#EXT-X-ENDLIST
Control key access permissions through token-bearing URLs:
#EXT-X-KEY:METHOD=AES-128,URI="https://example.com/key?token=eyJhbGciOiJIUzI1NiJ9..."
The key server should implement the following verification mechanisms:
Proper server configuration is crucial for the normal operation of HLS encryption.
location /keys/ {
alias /path/to/keys/;
# Verify Token
if ($arg_token = "") {
return 403;
}
# Prevent caching keys
add_header Cache-Control "no-store, no-cache, must-revalidate";
add_header Pragma "no-cache";
# CORS configuration
add_header Access-Control-Allow-Origin "*";
}
Ensure the player can obtain keys and segments across domains:
location /hls/ {
add_header Access-Control-Allow-Origin "*";
add_header Access-Control-Allow-Methods "GET, HEAD";
add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";
types {
application/vnd.apple.mpegurl m3u8;
video/mp2t ts;
}
}
Different players have different levels of support for HLS encryption.
HLS.js is the most commonly used HLS player library on the web, supporting AES-128 encryption:
const hls = new Hls({
// Custom xhr request, can be used to add authentication headers
xhrSetup: function(xhr, url) {
if (url.includes('.key')) {
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
}
}
});
hls.loadSource('https://example.com/encrypted.m3u8');
hls.attachMedia(video);
All M3U8 files, TS segments, and key requests should be transmitted over HTTPS to prevent man-in-the-middle attacks from stealing keys.
Don't use fixed key filenames; use dynamically generated token-bearing URLs, generating different key links for each playback.
Key tokens should have a reasonable validity period, usually set to the video duration plus some buffer time, to prevent tokens from being abused long-term.
For high-value content, it is recommended to combine with professional DRM systems like Widevine and FairPlay to provide stronger content protection.
Record key request logs, monitor abnormal request patterns, and timely detect and respond to hotlinking behavior.
Embed digital watermarks in videos so that even if content is recorded, the source of leakage can be traced.
HLS encryption is an important means of protecting video content security. AES-128 has the best compatibility, and SAMPLE-AES has better performance. In practical applications, it is necessary to select an appropriate encryption scheme based on specific security requirements, terminal devices, and performance requirements.
At the same time, key management is the core of the entire encryption system. It must be combined with complete identity verification, authorization mechanisms, and security policies to truly achieve the goal of content protection.
More great articles and useful tools
Master the core technology of HLS streaming media playback, including working principles, basic code examples, common configurations, event listening, and error handling.
Read More →In-depth explanation of video CDN acceleration principles and optimization methods, including caching strategies, bandwidth control, edge computing, pre-caching, and cost optimization recommendations.
Read More →Comprehensive introduction to mobile video playback optimization tips, including autoplay restrictions, mute strategies, gesture control, landscape/portrait switching, and performance battery optimization.
Read More →Use our free M3U8 online player, supports encrypted HLS stream playback, test directly in your browser
Try It Now ➡