@ltlovezh
2021-01-09T11:28:25.000000Z
字数 1991
阅读 2678
ffmpeg
通过FFmpeg解封装或者封装Mp4容器时,可以进行解密或者加密,这是MP4容器提供的能力。
libavformat/movenc.c
:提供了mov、3gp、mp4、psp、3g2、ipod、ismv和f4v的Muxer。libavformat/mov.c
:提供了mov、mp4、m4a、3gp、3g2和mj2的Demuxer。针对加密,libavformat/movenc.c提供了三个参数:
{ "encryption_scheme", "Configures the encryption scheme, allowed values are none, cenc-aes-ctr", offsetof(MOVMuxContext, encryption_scheme_str), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
{ "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
{ "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
加密时,需要指定上面三个参数。
针对解密,libavformat/mov.c提供了一个参数:
{ "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM }
解密时,只要指定一个decryption_key
就可以了。
加密一个文件:
ffmpeg -i decryption.mp4 -vcodec copy -acodec copy -encryption_scheme cenc-aes-ctr -encryption_key c7e16c4403654b85847037383f0c2db3 -encryption_kid a7e61c373e219033c21091fa607bf3b8 encryption.mp4
播放加密的mp4文件:
ffplay -i encryption.mp4 -decryption_key c7e16c4403654b85847037383f0c2db3
针对加密的mp4文件,解密出一个未加密文件:
ffmpeg -decryption_key c7e16c4403654b85847037383f0c2db3 -i encryption.mp4 decryption.mp4
加密:
AVDictionary *opts = NULL;
// 指定加密参数
av_dict_set(&format_opts, "encryption_scheme", "cenc-aes-ctr", 0);
av_dict_set(&format_opts, "encryption_key", "c7e16c4403654b85847037383f0c2db3", 0);
av_dict_set(&format_opts, "encryption_kid", "a7e61c373e219033c21091fa607bf3b8", 0);
ret = avformat_write_header(AVFormatContext, &format_opts);
解密:
AVDictionary *format_opts = NULL;
// 指定解密key
av_dict_set(&format_opts, "decryption_key", "c7e16c4403654b85847037383f0c2db3", 0);
err = avformat_open_input(&AVFormatContext, "path", AVInputFormat, &format_opts);
加密前的Mp4 Box:
加密后的Mp4 Box:
相比于原始文件,加密文件在stbl下新增加了3个box: