Encrypt Media Files Using FFmpeg Crypto Protocol

Learn how to secure your media files using FFmpeg’s built-in crypto protocol. This article covers the step-by-step process of generating AES-128 encryption keys and initialization vectors (IVs), executing the FFmpeg encryption command, and decrypting the media back to its original format for playback.

Step 1: Generate a Key and Initialization Vector (IV)

The FFmpeg crypto protocol uses AES-128 encryption in Cipher Block Chaining (CBC) mode. This requires a 128-bit (16-byte) secret key and a 16-byte Initialization Vector (IV). Both must be provided to FFmpeg as 32-character hexadecimal strings.

You can generate strong, random hexadecimal keys using OpenSSL in your terminal:

# Generate a 16-byte random key
openssl rand -hex 16

# Generate a 16-byte random IV
openssl rand -hex 16

For the following examples, we will use these sample values: * Key: 0123456789abcdef0123456789abcdef * IV: fedcba9876543210fedcba9876543210

Step 2: Encrypt the Media File

To encrypt a video or audio file, prefix the output file path with crypto: or crypto+file:. You must pass the hex key and IV to FFmpeg using the -key and -iv flags.

Run the following command to encrypt an MP4 video:

ffmpeg -i input.mp4 -c copy -key 0123456789abcdef0123456789abcdef -iv fedcba9876543210fedcba9876543210 -f mp4 crypto:encrypted.mp4

Command Breakdown:

The resulting encrypted.mp4 file will be fully encrypted and unplayable by standard media players.

Step 3: Decrypt the Media File

To restore the encrypted file to a playable format, or to stream it directly into an application, use the crypto: protocol prefix on the input file. Provide the key and IV using the -decryption_key and -decryption_iv flags.

Run this command to decrypt the file:

ffmpeg -decryption_key 0123456789abcdef0123456789abcdef -decryption_iv fedcba9876543210fedcba9876543210 -i crypto:encrypted.mp4 -c copy decrypted.mp4

Command Breakdown: