Halaman ini belum tersedia dalam bahasa lokal Anda. Kami berusaha keras untuk menambahkan lebih banyak versi bahasa. Terima kasih atas dukungan Anda.

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
Help Center/ Video On Demand/ Best Practices/ Protecting Videos with HLS Encryption

Protecting Videos with HLS Encryption

Updated on 2024-01-25 GMT+08:00

Environment Preparation

You have downloaded the SDK.

Scenario Description

Hotlink protection prevents unauthorized users from downloading or playing VOD content. However, this cannot prevent malicious paid users from downloading the content to their local PCs for secondary distribution.

To address this issue, Huawei Cloud VOD provides HLS encryption. With HLS encryption enabled, encrypted videos cannot be distributed to others even if they are downloaded by malicious users. HLS encryption requires the key service and token generation service. Therefore, this solution is suitable for those who can deploy authentication and key management servers by themselves.

Implementation

HLS encryption provided by Huawei Cloud VOD uses the AES-128 encryption algorithm to encrypt each TS file. The generated M3U8 file describes how the player decrypts the TS file. All HLS players are supported.

In this solution, VOD integrates Huawei Cloud Key Management Service (KMS) to provide keys for HLS encryption.

  • Encryption
    1. You upload a video to VOD and request HLS encryption.
    2. VOD requests the encryption key from KMS and stores the obtained key ID and key ciphertext.
    3. VOD sends an HLS encryption request to Media Processing Center (MPC). MPC encrypts the video during transcoding.

      The M3U8 file generated after transcoding contains the #EXT-X-KEY tag, which contains the METHOD and URI attributes. URI is the address of your key management server.

      NOTE:

      If the streaming URL used after encryption is HTTPS, the KMS URL must also be HTTPS. Otherwise, the playback cannot be previewed on the VOD console.

      #EXTM3U  
      #EXT-X-VERSION:3  
      #EXT-X-TARGETDURATION:6  
      #EXT-X-MEDIA-SEQUENCE:0 
      #EXT-X-KEY:METHOD=AES-128,URI="https://domain-sample/encrypt/get-key?asset_id=6aee80009c4ca6970f508d6334194794",IV=0x80a3ff24ccd788042ca7f2237e74c59d  
      #EXTINF:5.000000,  6aee80009c4ca6970f508d6334194794_1_1920X1080_3000_0_0.ts  
      #EXTINF:5.000000,  6aee80009c4ca6970f508d6334194794_1_1920X1080_3000_0_1.ts  
      #EXT-X-ENDLIST
    4. VOD uses CDN to accelerate the distribution of encrypted HLS video files.
  • Encryption
    1. When an end user logs in to a player, your server verifies user identity. If the verification succeeds, your server allocates a token and returns the playback URL containing the token to the player.

      For example, if the video playback URL is https://1280.cdn-vod.huaweicloud.com/input/test.m3u8, the playback URL returned to the player is https://1280.cdn-vod.huaweicloud.com/input/test.m3u8?token={token}.

    2. The player sends a playback request containing the obtained playback URL to CDN. The token is dynamic. Therefore, after receiving the request, CDN directly retrieves the content from VOD. VOD writes the token in the request URL to the URI of the M3U8 file.

      The M3U8 file returned by VOD to CDN contains the token value of the player. The following is an example:

      #EXTM3U  
      #EXT-X-VERSION:3  
      #EXT-X-TARGETDURATION:6  
      #EXT-X-MEDIA-SEQUENCE:0 
      #EXT-X-KEY:METHOD=AES-128,URI="https://domain-sample/encrypt/get-key?asset_id=6aee80009c4ca6970f508d6334194794&token={token}",IV=0x80a3ff24ccd788042ca7f2237e74c59d  
      #EXTINF:5.000000,  6aee80009c4ca6970f508d6334194794_1_1920X1080_3000_0_0.ts  
      #EXTINF:5.000000,  6aee80009c4ca6970f508d6334194794_1_1920X1080_3000_0_1.ts  
      #EXT-X-ENDLIST
    3. The player parses the M3U8 file to obtain the URI in the EXT-X-KEY tag and requests the key.
    4. Your key management server verifies the token. If the token is valid, the server calls the key query API.

      Your server can cache the key locally. If another playback device requests the key, it can directly return the key without obtaining the key from VOD.

    5. Your server returns the key to the player. The player uses the key to decrypt the M3U8 file and start playing the media.

Building Related Services

To use HLS encryption, you need to deploy the key management server and token generation service.

  • The key management server needs to have the following functions. See Sample Code.
    • Identity authentication. As described in Implementation, your key management server verifies whether the token is valid upon receiving a key request.
    • Key acquisition from VOD. Keys are stored in VOD. Therefore, your key management server needs to call a VOD API to obtain the key.
    • Key acquisition from cache. Your key management server should have the cache function to cache the obtained key to avoid frequent access to VOD.
  • Token generation service. When an end user logs in to your playback device, your server verifies the identity, generates a token, and returns the playback URL containing the token to the playback device. For details about the sample code for generating a token, see Sample Code.

    The generated token must contain uppercase letters, lowercase letters, and digits. The length can be customized. A unique token is allocated for each login and the token has a validity period. Comply with the least privilege principle. It is recommended that the token be used only for HLS-encrypted videos.

Video Encryption

  1. Upload the video file to be encrypted.

    If the video to be encrypted has not been uploaded, you can upload the video to VOD on the console.

  2. Configure the key URL.

    Before encryption, add the address of the key management server built in Building Related Services to VOD. During encryption, the address is written to the generated M3U8 file.
    1. Log in to the VOD console. In the navigation pane, choose Global Settings > Security.
    2. Click HLS Encryption Settings. In the dialog box displayed, enter the URL of your key management server, for example, https://domain-sample/encrypt/get-key.
    3. Click OK.

  3. Create a transcoding template.

    HLS encryption is implemented during transcoding. Therefore, before transcoding, you need to create a transcoding template with encryption enabled.
    1. In the navigation pane, choose Global Settings > Transcoding Templates.
    2. Click Create Custom Template Group. On the displayed page, configure related parameters.

      In the Basic Information area, set Output Format to HLS, enable encryption, and set other parameters based on your needs. For details, see Transcoding Settings.

    3. Click OK.

  4. Encrypt the video.

    1. In the navigation pane, choose Audio and Video Management.
    2. Select the video that requires HLS encryption and click Transcode.
    3. In the dialog box displayed, select the transcoding template created in step 3 and click OK.

      The system starts transcoding the video. If Transcoding Status in the Status column becomes Completed, the transcoding succeeds and the video has been encrypted.

Video Playback

This solution uses the HLS standard for encryption. All players that support HLS can decrypt and play content.

  1. Log in to the VOD console. In the navigation pane, choose Audio and Video Management.
  2. Click Details in the row contains the encrypted video and then click the Playback tab.
  3. Click to play the video.

  4. Enable developer mode in your browser. You can see that the console requests the key using the configured URL and decrypts the video for playback.

Sample Code

  • Sample code for key management server

    In this example, a Universally Unique Identifier (UUID) is used to generate a token. You can also select a generation method. The sample code does not include validity check for login users, which you can do on your own if necessary.

    When your key management server receives a key request, it checks whether the decryption key is stored in the cache. If not, the server calls the server SDK to query the key.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    import java.util.Base64;
    import java.util.UUID;
    
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.huawei.kms.initvodclient.VodClientFactory;
    import com.huawei.kms.util.CacheUtils;
    import com.huaweicloud.sdk.vod.v1.model.ShowAssetCipherRequest;
    
    import retrofit2.http.Header;
    
    @RestController
    public class KeyManagerController {
        /**
         * Assign a token to a legitimate user and return the playback URL with the token.
         *
         * @param accessToken Authentication information carried with the user. Verify the identity.
         * @param playUrl     Playback URL
          * @return Return the playback URL with the token.
         */
        @GetMapping("/get-url")
        public String getTokenPlayUrl(@Header("access-token") String accessToken,
                @RequestParam(value = "play_url", required = true) String playUrl) {
             // Assign a token to a valid terminal. ***** needs to be generated by the code on the customer side.
            String token = "*****";
             // Construct the playback URL with the token included and return it. http://{domain}/asset/{asset_id}/play_video/index.m3u8?token={token}
            return playUrl.substring(0, playUrl.lastIndexOf("/") + 1) +
                    playUrl.substring(playUrl.lastIndexOf("/") + 1) + "?token=" + token;
        }
    
    
        /**
          * @param asset_id Media ID
         * @param token    Token assigned to the user, where you need to check whether the token is valid. Return the key to those who pass the verification.
         * @param response
         * @return Return the key of the byte array type.
         */
        @GetMapping(value = "/get-key",headers = "Accept=application/octet-stream")
        public byte[] getKey(@RequestParam(value = "asset_id", required = true) String asset_id,
                @RequestParam(value = "token", required = true) String token, HttpServletResponse response) {
            // Get the key from the cache. If it is not in the cache, obtain it from VOD. In this example, suppose you store the key in the cache database.
            String key = CacheUtils.getCipherFromCache(asset_id);
            if (StringUtils.isEmpty(key)) {
                ShowAssetCipherRequest request = new ShowAssetCipherRequest();
                request.withAssetId(asset_id);
                key = VodClientFactory.getClient().showAssetCipher(request).getDk();
                // Cross-domain. Enter the actual site or fill in *.
                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Content-Length", "16");
                // Set the data type of the key.
                response.setHeader("Content-Type", "application/octet-stream");
                // Update the cache.
                CacheUtils.updateCipherFromCache(asset_id, key);
            }
            return Base64.getDecoder().decode(key);
        }
    }
    
  • Obtaining the VodClient Sample Code
    import com.huaweicloud.sdk.core.auth.BasicCredentials;
    import com.huaweicloud.sdk.core.auth.ICredential;
    import com.huaweicloud.sdk.vod.v1.VodClient;
    import com.huaweicloud.sdk.vod.v1.region.VodRegion;
    
    public class VodClientFactory {
    
        private final static String AK = System.getenv("CLOUD_SDK_AK");
        private final static String SK = System.getenv("CLOUD_SDK_SK");
        private final static String REGION="cn-north-4"; // Actual service node, for example, cn-north-1 and cn-east-2
    
        private static volatile VodClient vodClient = null;
    
        public static VodClient getClient() {
            if (vodClient == null) {
                synchronized (VodClient.class) {
                    if (vodClient == null) {         
                        ICredential auth = new BasicCredentials()               
                                   .withAk(AK)               
                                   .withSk(SK);         
                        vodClient = VodClient.newBuilder().withCredential(auth)               
                                   .withRegion(VodRegion.valueOf(REGION))               
                                   .build();      
                     }   
                 }
             }
             return vodClient;
        }
    }
  • Sample code for caching
    After your key management server obtains the decryption key from VOD, it needs to cache the key to avoid repeated requests for the same media from VOD. In this example, suppose you cache the key on your local PC. You can also cache it in the database.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    import com.google.common.cache.Cache;
    import com.google.common.cache.CacheBuilder;
    
    import java.util.concurrent.TimeUnit;
    
    public class CacheUtils {
    
        private static Cache<String, String> cipherCache = CacheBuilder.newBuilder()
                .maximumSize(100) // Set the maximum cache size.
                .expireAfterWrite(10, TimeUnit.MINUTES) // Set the cache to be invalid one minute after data is written.
                .concurrencyLevel(10) // Set the concurrency level to 10.
                .recordStats() // Enable cache statistics.
                .build();
    
        public static String getCipherFromCache(String key) {
            return cipherCache.getIfPresent(key);
        }
    
        public static void updateCipherFromCache(String key, String value) {
            cipherCache.put(key, value);
        }
    }
    
  • The Maven dependency required by the preceding sample code is as follows:

    Note: The following JAR package versions are not fixed. Use the actual versions of the Java project and JAR packages.

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.12.RELEASE</version>
        <relativePath/>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.7</version>
        </dependency>
        <dependency>
            <groupId>com.huaweicloud.sdk</groupId>
            <artifactId>huaweicloud-sdk-vod</artifactId>
            <version>3.1.72</version>
        </dependency>
        <dependency>
            <groupId>com.squareup.retrofit2</groupId>
            <artifactId>retrofit</artifactId>
            <version>2.5.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>27.0.1-jre</version>
        </dependency>
    </dependencies>

Kami menggunakan cookie untuk meningkatkan kualitas situs kami dan pengalaman Anda. Dengan melanjutkan penelusuran di situs kami berarti Anda menerima kebijakan cookie kami. Cari tahu selengkapnya

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback