CGJU
CGJU
May 12, 2026 · 7 min read

HLS Encryption Overview

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 Principles

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.

Encryption Process

  1. Key Generation: Generate encryption key (Key) and initialization vector (IV)
  2. Content Encryption: Encrypt TS segments using the key
  3. Playlist Update: Add encryption information tags to the M3U8 file
  4. Key Distribution: Provide the key to authorized users through secure channels
  5. Playback Decryption: The player decrypts and plays after obtaining the key

M3U8 Encryption Tags

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 Encryption Implementation

AES-128 is the most basic and best compatibility encryption method for HLS, encrypting the entire TS segment.

Generating Encryption Keys

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

FFmpeg Encryption Command

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

Creating Key Information File

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 Encryption

SAMPLE-AES is another HLS encryption method proposed by Apple, which encrypts only part of the media samples, reducing performance overhead while ensuring security.

Features of SAMPLE-AES

  • Partial encryption: Only encrypts the first 16 bytes of each sample, not the entire segment
  • Better performance: Less encryption/decryption computation, suitable for low-performance devices
  • Good Apple ecosystem support: Native support on iOS, Apple TV and other devices
  • Sufficient security: For most scenarios, partial encryption is sufficient to protect content

FFmpeg SAMPLE-AES Encryption

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 Strategies

Key management is the most critical part of the HLS encryption system. Once the key is leaked, encryption loses its meaning.

Key Rotation

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

Token-Based Key Access

Control key access permissions through token-bearing URLs:

#EXT-X-KEY:METHOD=AES-128,URI="https://example.com/key?token=eyJhbGciOiJIUzI1NiJ9..."

Server-Side Key Verification

The key server should implement the following verification mechanisms:

  • User authentication: Verify if the user is logged in
  • Content authorization verification: Verify if the user has permission to watch the video
  • Token validity period: Set the expiration time of the key URL
  • IP whitelist: Restrict keys to be obtained only from specified IPs
  • Referer check: Prevent key links from being directly referenced

Server Configuration

Proper server configuration is crucial for the normal operation of HLS encryption.

Nginx Key Service Configuration

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 "*";
}

CORS Configuration

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;
    }
}

Player Support

Different players have different levels of support for HLS encryption.

Native Support

  • Safari (macOS/iOS): Native support for AES-128 and SAMPLE-AES
  • AVPlayer (iOS/tvOS): Full support for HLS encryption
  • ExoPlayer (Android): Supports AES-128 encryption

HLS.js Support

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);

Security Best Practices

1. Use HTTPS

All M3U8 files, TS segments, and key requests should be transmitted over HTTPS to prevent man-in-the-middle attacks from stealing keys.

2. Dynamic Key URLs

Don't use fixed key filenames; use dynamically generated token-bearing URLs, generating different key links for each playback.

3. Set Key Validity Period

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.

4. Combine with DRM Systems

For high-value content, it is recommended to combine with professional DRM systems like Widevine and FairPlay to provide stronger content protection.

5. Monitor Key Requests

Record key request logs, monitor abnormal request patterns, and timely detect and respond to hotlinking behavior.

6. Watermark Technology Cooperation

Embed digital watermarks in videos so that even if content is recorded, the source of leakage can be traced.

Summary

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.

Related Recommendations

More great articles and useful tools

Want to Test HLS Playback?

Use our free M3U8 online player, supports encrypted HLS stream playback, test directly in your browser

Try It Now ➡