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 16For 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.mp4Command Breakdown:
-i input.mp4: Specifies the input media file.-c copy: Copies the video and audio streams directly without re-encoding, preserving original quality and speed.-key: The 32-character hex encryption key.-iv: The 32-character hex initialization vector.-f mp4: Force-specifies the output muxer format (required when using thecrypto:protocol prefix).crypto:encrypted.mp4: Instructs FFmpeg to route the output through the crypto protocol layer before writing it to disk.
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.mp4Command Breakdown:
-decryption_key: The hex key used during encryption.-decryption_iv: The hex IV used during encryption.-i crypto:encrypted.mp4: Tells FFmpeg to decrypt the input file on the fly as it reads it.decrypted.mp4: The output destination for the decrypted, playable media file.