Protecting Videos with HLS Encryption
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
- You upload a video to VOD and request HLS encryption.
- VOD requests the encryption key from KMS and stores the obtained key ID and key ciphertext.
- 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.
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
- VOD uses CDN to accelerate the distribution of encrypted HLS video files.
- Encryption
- 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}.
- 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
- The player parses the M3U8 file to obtain the URI in the EXT-X-KEY tag and requests the key.
- 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.
- Your server returns the key to the player. The player uses the key to decrypt the M3U8 file and start playing the media.
- 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.
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
- 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.
- 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.
- Log in to the VOD console. In the navigation pane, choose Global Settings > Security.
- 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.
- Click OK.
- Create a transcoding template.
HLS encryption is implemented during transcoding. Therefore, before transcoding, you need to create a transcoding template with encryption enabled.
- In the navigation pane, choose Global Settings > Transcoding Templates.
- 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.
- Click OK.
- Encrypt the video.
- In the navigation pane, choose Audio and Video Management.
- Select the video that requires HLS encryption and click Transcode.
- 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.
- Log in to the VOD console. In the navigation pane, choose Audio and Video Management.
- Click Details in the row contains the encrypted video and then click the Playback tab.
- Click to play the video.
- 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>
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot