[关闭]
@ltlovezh 2021-01-09T03:28:25.000000Z 字数 1991 阅读 2531

FFmpeg Mp4加解密

ffmpeg


基础知识

通过FFmpeg解封装或者封装Mp4容器时,可以进行解密或者加密,这是MP4容器提供的能力。

针对加密,libavformat/movenc.c提供了三个参数:

  1. { "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 },
  2. { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
  3. { "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提供了一个参数:

  1. { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM }

解密时,只要指定一个decryption_key就可以了。

命令行操作

加密一个文件:

  1. ffmpeg -i decryption.mp4 -vcodec copy -acodec copy -encryption_scheme cenc-aes-ctr -encryption_key c7e16c4403654b85847037383f0c2db3 -encryption_kid a7e61c373e219033c21091fa607bf3b8 encryption.mp4

播放加密的mp4文件:

  1. ffplay -i encryption.mp4 -decryption_key c7e16c4403654b85847037383f0c2db3

针对加密的mp4文件,解密出一个未加密文件:

  1. ffmpeg -decryption_key c7e16c4403654b85847037383f0c2db3 -i encryption.mp4 decryption.mp4

代码实现

加密:

  1. AVDictionary *opts = NULL;
  2. // 指定加密参数
  3. av_dict_set(&format_opts, "encryption_scheme", "cenc-aes-ctr", 0);
  4. av_dict_set(&format_opts, "encryption_key", "c7e16c4403654b85847037383f0c2db3", 0);
  5. av_dict_set(&format_opts, "encryption_kid", "a7e61c373e219033c21091fa607bf3b8", 0);
  6. ret = avformat_write_header(AVFormatContext, &format_opts);

解密:

  1. AVDictionary *format_opts = NULL;
  2. // 指定解密key
  3. av_dict_set(&format_opts, "decryption_key", "c7e16c4403654b85847037383f0c2db3", 0);
  4. err = avformat_open_input(&AVFormatContext, "path", AVInputFormat, &format_opts);

Box差异

加密前的Mp4 Box:
加密前

加密后的Mp4 Box:
加密后

相比于原始文件,加密文件在stbl下新增加了3个box:

  1. senc:sample specific encryption data,特定加密数据样本。
  2. saio:sample auxiliary information offsets,样本辅助信息偏移量。
  3. saiz:sample auxiliary information sizes,样本辅助信息大小。
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注