シナリオ
HTTP-Live-Streaming (HLS) encryption is applicable to basic data protection scenarios such as protecting your videos from illegal download or distribution.
制限事項
- HLS暗号化を使用するには、SubmitJobsメソッドを呼び出す必要があります。
- Base64アルゴリズムは、メディアワークフローでのHLS暗号化には使用できません。
依存関係
- ApsaraVideo Media Processing (MPS) SDK for Javaをインストールします。 詳細については、「インストール」をご参照ください。
- 他の依存関係を追加します。
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.25</version </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency>
Base64アルゴリズムを使用したHLS暗号化のサンプルコード
com.alibaba.fastjson.JSONArrayをインポートします。com.alibaba.fastjson.JSONObjectをインポートします。com.alibaba.mediaprocess.mpsDocTestShanghai.Configをインポートします。com.aliyuncs.DefaultAcsClientをインポートします。com.aliyuncs.exceptions.ClientExceptionをインポートします。com.aliyuncs.mts.mo del.v20140618.SubmitJobsRequestをインポートします。com.aliyuncs.mts.mo del.v20140618.SubmitJobsResponseをインポートします。com.aliyuncs.profile.DefaultProfileをインポートします。impor t org.apache.com mons.codec.binary.Base64;
java.io.UnsupportedEncodingExceptionをインポートします。impor t java.net.URLEncoder;
パブリッククラスDataEncryptionBasicBase64 {
private static String accessKeyId = "***"; // The AccessKey ID of the RAM user.
private static String accessKeySecret = "***"; // RAMユーザーのAccessKeyシークレット。
プライベート静的文字列mpsRegionId="cn-shanghai"; // MPSサービスを使用するリージョンのID。
private DefaultAcsClient client = null;
private final String location = "oss-cn-shanghai"; // The location information about the region in which the Object Storage Service (OSS) buckets reside. 必要に応じてこのパラメーターを設定します。
private final String ossInputBucket = "huadong2-test"; // 入力ファイルが保存されているOSSバケットの名前。 必要に応じてこのパラメーターを設定します。
private final String ossOutputBucket = "huadong2output"; // 出力ファイルが格納されているOSSバケットの名前。 必要に応じてこのパラメーターを設定します。
private final String pipelineId = "f24c8a87a497456898b467892eea84d6"; // MPSキューのID。 必要に応じてこのパラメーターを設定します。
パブリックDataEncryptionBasicBase64() がClientException {
DefaultProfile profile = DefaultProfile.getProfile(
mpsRegionId, // MPSサービスを使用するリージョンのID。
accessKeyId, // RAMユーザーのAccessKey ID。
accessKeySecret); // RAMユーザーのAccessKeyシークレット。
this.client = new DefaultAcsClient(profile);
}
private JSONObject getInputFile() {
JSONObject inputFile = new JSONObject();
inputFile.put("Location" 、location);
inputFile.put("バケット" 、ossInputBucket);
try {
inputFile.put("オブジェクト" 、URLEncoder.encode("wb-ceshi/487_93.mp4" 、"utf-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("input URL encode failed");
}
return inputFile;
}
プライベートJSONArray getOutputs() throws ClientException {
JSONArray outputs = new JSONArray();
outputs.add(getOutput());
return outputs;
}
プライベートJSONObject getOutput() throws ClientException {
JSONObject output = new JSONObject();
output.put("OutputObject", "wb-ceshi/202011131343");
output.put("TemplateId" 、"S00000001-100000");
output.put("Encryption", getEncryptionConfigs());
return output;
}
プライベートJSONObject getEncryptionConfigs() throws ClientException {
JSONObject encryption = new JSONObject();
encryption.put("Type", "hls-aes-128");
// 暗号化キーの長さは16バイトである必要があります。
encryption.put("Key", Base64.encodeBase64URLSafeString("encryptionkey128".getBytes()));
文字列url="http:// 127.0.0.1:8888/";
encryption.put("KeyUri", Base64.encodeBase64URLSafeString(url.getBytes()));
encryption.put("KeyType", "Base64");
return encryption;
}
private String submitJobs() throws ClientException {
JSONObject inputFile = getInputFile();
SubmitJobsRequest request = new SubmitJobsRequest();
request.setInput(inputFile.toJSONString());
request.setOutputLocation (場所);
request.setOutputBucket(ossOutputBucket);
request.setOutputs(getOutputs().toJSONString());
request.setPipelineId(pipelineId);
SubmitJobsResponse reponse = this.client.getAcsResponse(request);
System.out.println(JSONObject.toJSONString(reponse.getJobResultList()));
return reponse.getJobResultList().get(0).getJob().getJobId();
}
public static void main(String[] args) throws ClientException {
DataEncryptionBasicBase64デモ=新しいDataEncryptionBasicBase64();
String jobId= demo.submitJobs();
System.out.println(jobId);
}
}
KMSを使用したHLS暗号化のサンプルコード
Key Management Service (KMS) を使用してHLS暗号化を実行するには、HLS暗号化を使用するメディアワークフローを作成する必要があります。 ワークフローが実行された後にのみ、SubmitJobsメソッドを呼び出してHLS暗号化を実行できます。 詳細については、「HLS 暗号化の実行および再生方法」をご参照ください。
com.alibaba.fastjson.JSONArrayをインポートします。com.alibaba.fastjson.JSONObjectをインポートします。com.alibaba.mediaprocess.mpsDocTestShanghai.Configをインポートします。com.aliyuncs.DefaultAcsClientをインポートします。com.aliyuncs.exceptions.ClientExceptionをインポートします。com.aliyuncs.kms.mo del.v20160120.GenerateDataKeyRequestをインポートします。com.aliyuncs.kms.mo del.v20160120.GenerateDataKeyResponseをインポートします。com.aliyuncs.mts.mo del.v20140618.SubmitJobsRequestをインポートします。com.aliyuncs.mts.mo del.v20140618.SubmitJobsResponseをインポートします。com.aliyuncs.profile.DefaultProfileをインポートします。impor t org.apache.com mons.codec.binary.Base64;
java.io.UnsupportedEncodingExceptionをインポートします。impor t java.net.URLEncoder;
パブリッククラスDataEncryptionBasicKMS {
private static String accessKeyId = "***"; // RAMユーザーのAccessKey ID。
private static String accessKeySecret = "***"; // RAMユーザーのAccessKeyシークレット。
プライベート静的文字列mpsRegionId="cn-shanghai"; // MPSサービスを使用するリージョンのID。
private DefaultAcsClient client = null;
private final String location = "oss-cn-shanghai"; // OSSバケットが存在するリージョンの位置情報。 必要に応じてこのパラメーターを設定します。
private final String ossInputBucket = "huadong2-test"; // 入力ファイルが保存されているOSSバケットの名前。 必要に応じてこのパラメーターを設定します。
private final String ossOutputBucket = "huadong2output"; // 出力ファイルが格納されているOSSバケットの名前。 必要に応じてこのパラメーターを設定します。
private final String pipelineId = "f24c8a87a497456898b467892eea84d6"; // MPSキューのID。 必要に応じてこのパラメーターを設定します。
public DataEncryptionBasicKMS() throws ClientException {
DefaultProfile profile = DefaultProfile.getProfile(
mpsRegionId, // MPSサービスを使用するリージョンのID。
accessKeyId, // RAMユーザーのAccessKey ID。
accessKeySecret); // RAMユーザーのAccessKeyシークレット。
this.client = new DefaultAcsClient(profile);
}
private JSONObject getInputFile() {
JSONObject inputFile = new JSONObject();
inputFile.put("Location" 、location);
inputFile.put("バケット" 、ossInputBucket);
try {
inputFile.put("オブジェクト" 、URLEncoder.encode("wb-ceshi/487_93.mp4" 、"utf-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("input URL encode failed");
}
return inputFile;
}
プライベートJSONArray getOutputs() throws ClientException {
JSONArray outputs = new JSONArray();
outputs.add(getOutput());
return outputs;
}
プライベートJSONObject getOutput() throws ClientException {
JSONObject output = new JSONObject();
output.put("OutputObject", "wb-ceshi/20201117");
output.put("TemplateId", "S00000001-100020");
output.put("Encryption", getEncryptionConfigs());
return output;
}
プライベートJSONObject getEncryptionConfigs() throws ClientException {
GenerateDataKeyRequest generateDataKeyRequest=新しいGenerateDataKeyRequest();
generateDataKeyRequest.setKeyId("504d60ef-93f3-48e8-9d94-075aeb7d7003"); // エイリアスがalias/acs/mtsである顧客マスターキー (CMK) に値を置き換えます。 KMSコンソールにログインしてCMKを表示できます。 KMSコンソールでキーリストを表示するには、https://kms.console.aliyun.com/cn-shanghai/key/listにアクセスします。
generateDataKeyRequest.setKeySpec("AES_128");
GenerateDataKeyResponse generateDataKeyResponse=client.getAcsResponse(generateDataKeyRequest);
JSONObject encryption = new JSONObject();
encryption.put("Type", "hls-aes-128");
encryption.put("キー", generateDataKeyResponse.getCiphertextBlob());
String url="http:// 127.0.0.1:8888/?Ciphertext=" + generateDataKeyResponse.getCiphertextBlob(); // 復号化URL。 必要に応じてこのパラメーターを設定します。
encryption.put("KeyUri", Base64.encodeBase64URLSafeString(url.getBytes()));
encryption.put("KeyType" 、"KMS");
return encryption;
}
private String submitJobs() throws ClientException {
JSONObject inputFile = getInputFile();
SubmitJobsRequest request = new SubmitJobsRequest();
request.setInput(inputFile.toJSONString());
request.setOutputLocation (場所);
request.setOutputBucket(ossOutputBucket);
request.setOutputs(getOutputs().toJSONString());
request.setPipelineId(pipelineId);
SubmitJobsResponse reponse = this.client.getAcsResponse(request);
System.out.println(JSONObject.toJSONString(reponse.getJobResultList()));
return reponse.getJobResultList().get(0).getJob().getJobId();
}
public static void main(String[] args) throws ClientException {
DataEncryptionBasicKMS demo = new DataEncryptionBasicKMS();
String jobId= demo.submitJobs();
System.out.println(jobId);
}
}
Base64アルゴリズムを使用した復号化のサンプルコード
impor t com.sun.net.httpserver.Headers;
impor t com.sun.net.httpserver.HttpExchange;
impor t com.sun.net.httpserver.HttpHandler;
impor t com.sun.net.httpserver.HttpServer;
impor t com.sun.net.httpserver.spi.HttpServerProvider;
java.io.IOExceptionをインポートします。java.io.OutputStreamをインポートします。impor t java.net.HttpURLConnection;
impor t java.net.InetSocketAddress;
パブリッククラスBase64DecryptServer {
/**
* 注:
* 1. 解読リクエストを受け取ります。
* 2. Base64アルゴリズムを使用してプレーンテキストキーをデコードし、デコードされたキーを返します。
*/
パブリッククラスBase64DecryptHandlerがHttpHandlerを実装 {
/**
* 復号化要求を処理します。
*
* @ param httpExchange
* @throws IOException
*/
public void handle(HttpExchange httpExchange) throws IOException {
System.out.println("request in");
String requestMethod = httpExchange.getRequestMethod();
if ("GET".equalsIgnoreCase(requestMethod)) {
// 復号化キーは暗号化キーと同じでなければなりません。
byte[] key = "encryptionkey128".getBytes();
// ヘッダーを設定します。
setHeader(httpExchange, key);
// Base64アルゴリズムを使用してデコードされた平文キーを返します。
OutputStream responseBody = httpExchange.getResponseBody();
System.out.println (新しい文字列 (キー));
responseBody.write(key);
responseBody.close();
}
}
private void setHeader(HttpExchange httpExchange, byte[] key) throws IOException {
Headers responseHeaders = httpExchange.getResponseHeaders();
responseHeaders.set("Access-Control-Allow-Origin", "*");
httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, key.length);
}
}
/**
* サービスを開始します。
*
* @throws IOException
*/
private void serviceBootStrap() がIOException {
HttpServerProvider provider = HttpServerProvider.provider();
// 30のリクエストを同時に受け入れることができるポート9999にリスナーを設定します。
HttpServer httpserver = provider.createHttpServer (新しいInetSocketAddress(8888) 、30);
httpserver.createContext("/", new Base64DecryptHandler());
httpserver.start();
System.out.println("hls decrypt server started");
}
public static void main(String[] args) throws IOException {
Base64DecryptServerサーバー=新しいBase64DecryptServer();
server.serviceBootStrap();
}
}
KMSを使用した復号化のサンプルコード
com.aliyuncs.DefaultAcsClientをインポートします。com.aliyuncs.exceptions.ClientExceptionをインポートします。com.aliyuncs.http.ProtocolTypeをインポートします。com.aliyuncs.kms.mo del.v20160120.DecryptRequestをインポートします。com.aliyuncs.kms.mo del.v20160120.DecryptResponseをインポートします。com.aliyuncs.profile.DefaultProfileをインポートします。impor t com.sun.net.httpserver.Headers;
impor t com.sun.net.httpserver.HttpExchange;
impor t com.sun.net.httpserver.HttpHandler;
impor t com.sun.net.httpserver.HttpServer;
impor t com.sun.net.httpserver.spi.HttpServerProvider;
impor t org.apache.com mons.codec.binary.Base64;
java.io.IOExceptionをインポートします。java.io.OutputStreamをインポートします。impor t java.net.HttpURLConnection;
impor t java.net.InetSocketAddress;
impor t java.net.URI;
java.util.regex.Matcherをインポートします。java.util.regex.Patternをインポートします。パブリッククラスHlsDecryptServer {
private static DefaultAcsClient client;
static {
String accessKeyId = "***"; // RAMユーザーのAccessKey ID。
String accessKeySecret = "***"; // RAMユーザーのAccessKeyシークレット。
String region = "cn-shanghai"; // KMSサービスを使用するリージョン。 このリージョンは、入力ファイルと出力ファイルが格納されているOSSバケットのリージョンと同じである必要があります。
client = new DefaultAcsClient(DefaultProfile.getProfile(region, accessKeyId, accessKeySecret));
}
/**
* 注:
* 1. 復号化要求を受信し、エンベロープデータ鍵 (EDK) およびセキュリティトークンを取得する。
* 2. KMSの復号化操作を呼び出して、データキー (DK) を取得します。
* 3. Base64アルゴリズムを使用してDKをデコードし、デコードされたDKを返します。
*/
パブリッククラスHlsDecryptHandlerがHttpHandlerを実装 {
/**
* 復号化要求を処理します。
*
* @ param httpExchange
* @throws IOException
*/
public void handle(HttpExchange httpExchange) throws IOException {
System.out.println("request in");
String requestMethod = httpExchange.getRequestMethod();
if ("GET".equalsIgnoreCase(requestMethod)) {
// セキュリティトークンが有効かどうかを確認します。
String token = getMtsHlsUriToken(httpExchange);
ブールvalidRe = validateToken(token);
if (!validRe) {
return;
}
// ビデオURLからEDKを取得します。
String ciphertext = getCiphertext(httpExchange);
if (null == ciphertext)
return;
// KMSの解読操作を呼び出してDKを取得し、Base64アルゴリズムを使用してDKをデコードします。
byte[] key = decrypt(ciphertext);
// ヘッダーを設定します。
setHeader(httpExchange, key);
// Base64アルゴリズムを使用してデコードされたDKを返します。
OutputStream responseBody = httpExchange.getResponseBody();
System.out.println (新しい文字列 (キー));
responseBody.write(key);
responseBody.close();
}
}
private void setHeader(HttpExchange httpExchange, byte[] key) throws IOException {
Headers responseHeaders = httpExchange.getResponseHeaders();
responseHeaders.set("Access-Control-Allow-Origin", "*");
httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, key.length);
}
/**
* KMSの復号化操作を呼び出してKMSからDKを受信した後、Base64アルゴリズムを使用してDKをデコードできます。
*
* @ param暗号文
* @return
*/
private byte[] decrypt(String ciphertext) {
DecryptRequest request = new DecryptRequest();
request.setCiphertextBlob(ciphertext);
request.setProtocol(ProtocolType.HTTPS);
try {
DecryptResponse response = client.getAcsResponse(request);
String plaintext = response.getPlaintext();
// 注: Base64アルゴリズムを使用してDKをデコードする必要があります。
return Base64.decodeBase64(plaintext);
} catch (ClientException e) {
e.printStackTrace();
ヌルを返します。
}
}
/**
* セキュリティトークンが有効かどうかを確認します。
*
* @ paramトークン
* @return
*/
private boolean validateToken(String token) {
if (null == token | | "".equals(token)) {
return false;
}
// TODO。 ロジックをカスタマイズして、トークンが有効かどうかを確認できます。
return true;
}
/**
* ビデオURLからEDKを取得します。
*
* @ param httpExchange
* @return
*/
private String getCiphertext(HttpExchange httpExchange) {
URI uri = httpExchange.getRequestURI();
String queryString = uri.getQuery();
String pattern = "Ciphertext=(\\w*)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(queryString);
if (m.find())
return m.group(1);
else {
System.out.println("Not Found Ciphertext Param");
ヌルを返します。
}
}
/**
* トークンパラメータを取得します。
*
* @ param httpExchange
* @return
*/
プライベート文字列getMtsHlsUriToken(HttpExchange httpExchange) {
URI uri = httpExchange.getRequestURI();
String queryString = uri.getQuery();
文字列パターン="MtsHlsUriToken=(\\w *)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(queryString);
if (m.find())
return m.group(1);
else {
System.out.println("Not Found MtsHlsUriToken Param");
ヌルを返します。
}
}
}
/**
* サービスを開始します。
*
* @throws IOException
*/
private void serviceBootStrap() がIOException {
HttpServerProvider provider = HttpServerProvider.provider();
// 一度に30のリクエストを受け入れることができるポート8888でリスナーを設定します。
HttpServer httpserver = provider.createHttpServer (新しいInetSocketAddress(8888) 、30);
httpserver.createContext("/", new HlsDecryptHandler());
httpserver.start();
System.out.println("hls decrypt server started");
}
public static void main(String[] args) throws IOException {
HlsDecryptServer server = new HlsDecryptServer();
server.serviceBootStrap();
}
}