FFMPEG Encryption

rickyma924 picture rickyma924 · Sep 23, 2015 · Viewed 16k times · Source

I am doing a project with encrypting video and I have a few questions for the procedure.

I used a command to transcode mp4 to HLS with a ts segment duration of ~10 seconds.

First, I need to encrypt those videos with a key from database. However, I have no idea for the encryption whether working with ffmpeg or not.

Second, if the encryption can work without ffmpeg, so what should I do? I have searched in google which includes something like openssl / aes but there is no a detailed step for me to follow, even the ffmpeg link: http://www.ffmpeg.org/ffmpeg-all.html#srtp

Could anyone give me a hand, teaching me how to encrypt a video? Thanks to you.

Answer

aergistal picture aergistal · Sep 23, 2015

Yes, you can do it with ffmpeg. You need to write the key from the database to a file, let's say video.key.

You need a second file, let's name it key_info which is the key info file. It has the following format:

key URI
key file path
IV (optional)

Eg:

http://example.com/video.key
video.key

You tell ffmpeg to use it to encrypt your segments with the hls_key_info argument:

ffmpeg -i input.mp4 -c copy -bsf:v h264_mp4toannexb -hls_time 10 -hls_key_info_file key_info playlist.m3u8

This will encrypt your segments with AES-128 in CBC mode and add the relevant tags to your playlist:

#EXT-X-KEY:METHOD=AES-128,URI="http://example.com/video.key"

You can also manually encrypt the segments if you want with openssl. Here's an example script, where each IV is equal to the segment index:

#!/bin/bash
ts_dir=/path/to/ts/

key_file=video.key
openssl rand 16 > $key_file
enc_key=$(hexdump -v -e '16/1 "%02x"' $key_file)

pushd $ts_dir

ts_cnt=$(ls *.ts | wc -l)
((ts_cnt--))

i=0
for i in $(seq -f "%01g" 0 $ts_cnt); do
    iv=$(printf '%032x' $i)
    ts_file=segment-$i.ts

    echo [$i] $ts_file

    openssl aes-128-cbc -e -in $ts_file -out encrypted_${ts_file} -nosalt -iv $iv -K $enc_key
done

popd