(转)Protected HLS using FFmpeg and OpenSSL

原作者:Prabath

转载自 Protected HLS using FFmpeg and OpenSSL 同时修正了一些错误;

This will walk you through creating Protected/ Encrypted hls stream using ffmpeg and openssl.

ffmpeg is a complete, cross-platform solution to record, convert and stream audio and video. It includes libavcodec – the leading audio/video codec library.

openssl : The OpenSSL Project is a collaborative effort to develop a robust, commercial-grade, full-featured, and Open Source toolkit implementing the Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) protocols as well as a full-strength general purpose cryptography library.

Protected HLS : is encrypted apple hls. It’s not a complete DRM solution. In this method segment files are encrypted using AES-128 bit
Im using a ubuntu 13.10 box.

Step 1 : Install openssl and ffmpeg

apt-get install openssl ffmpeg

Step 2 : segment your video file for hls playback.

ffmpeg -i $input -vcodec libx264 -acodec libvo_aacenc -b:v 128k -flags -global_header -map 0:0 -map 0:1 -f segment -segment_time 4 -segment_list_size 0 -segment_list list.m3u8 -segment_format mpegts stream%d.ts

Here $input is input video file. This command will create a list of streamxx.ts files and list.m3u8file. You can open this m3u8 file in a hls supported player or on a android/ios devices through a web service to confirm segments are working. (Note: segments should be on the same folder as m3u8 file)

Step 3 : encrypt the segments.
Create following bash script in the same folder and execute it to encrypt segments.

#!/bin/bash
keyFile=video.key
openssl rand 16 > $keyFile
encryptionKey=`cat $keyFile | hexdump -e '16/1 "%02x"'`
echo KEY: $encryptionKey
splitFilePrefix=sample
playlistFile=$splitFilePrefix.m3u8
encryptedFolder=encrypto
encryptedSplitFilePrefix="${encryptedFolder}/${splitFilePrefix}"
rm -rf $encryptedFolder
mkdir $encryptedFolder
numberOfTsFiles=`ls ${splitFilePrefix}*.ts | wc -l`
echo TSnum: $numberOfTsFiles
for (( i=0; i<$numberOfTsFiles; i++ ))
do
tsNumber=`printf '%03d' $i`
initializationVector=`printf '%032x' $i`
openssl aes-128-cbc -e -in ${splitFilePrefix}_$tsNumber.ts -out ${encryptedSplitFilePrefix}_$tsNumber.ts -nosalt -iv $initializationVector -K $encryptionKey
echo "${splitFilePrefix}_$tsNumber.ts ===> ${encryptedSplitFilePrefix}_$tsNumber.ts"
done
cp $playlistFile $encryptedFolder
mv $keyFile $encryptedFolder
echo encrypted HLS segments is in $encryptedSplitFilePrefix folder.

Step 4 : move/copy video.key and list.m3u8 to enc folder and modify the list.
m3u8 as follow (use gedit or notepad),

#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-ALLOW-CACHE:YES
#EXT-X-KEY:METHOD=AES-128,URI="video.key"
#EXT-X-TARGETDURATION:9
just insert the #EXT-X-KEY line and leave the rest as it is.

All done, now simply open the m3u8 file using a supported player or iphone/android device. I tested this successfully on a Android 4.2 device just few seconds ago. Good Luck.