Basic knowledge of

The Mp4 container can be decrypted or encrypted when it is decapsulated or encapsulated by FFmpeg, which is the capability provided by the Mp4 container.

  • libavformat/movenc.c: Offers Muxer for MOV, 3GP, MP4, PSP, 3G2, iPod, ISMV and F4V.
  • libavformat/mov.cDemuxer for MOV, MP4, M4A, 3GP, 3G2 and MJ2 is available.

For encryption, libavformat/movenc.c provides three arguments:

{ "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 },
Copy the code

The preceding three parameters must be specified for encryption.

For decryption, libavformat/mov.c provides an argument:

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

To decrypt, just specify a decryption_key.

Command line operation

Encrypt a file:

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

Play Encrypted MP4 Files:

ffplay -i encryption.mp4 -decryption_key c7e16c4403654b85847037383f0c2db3
Copy the code

For encrypted MP4 files, decrypt an unencrypted file:

ffmpeg -decryption_key c7e16c4403654b85847037383f0c2db3 -i encryption.mp4 decryption.mp4
Copy the code

Code implementation

Encryption:

AVDictionary *opts = NULL;
// Specify encryption parameters
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);
Copy the code

Decryption:

AVDictionary *format_opts = NULL;
// Specify the decryption key
av_dict_set(&format_opts, "decryption_key"."c7e16c4403654b85847037383f0c2db3".0);
err = avformat_open_input(&AVFormatContext, "path", AVInputFormat, &format_opts);
Copy the code

Box difference

Mp4 | Box: Before Encryption

Mp4 With Encryption

Compared to the original file, the encrypted file has 3 new boxes under STBL:

  1. Senc: sample specific encryption data.
  2. Saio: Sample auxiliary information offsets
  3. Saiz: Sample auxiliary information Sizes.