I am trying to encrypt a video file with with AES 256 CBC mode and using AWS KMS to encrypt the AES data key that was used to encrypt the video file. I have pass this encrypted file to AWS MediaConvert, it should decrypt the video on fly then transcode it.
After encrypting the video using following code I am encoding encrypted data key and Initialization vector with Base64 because it is mandatory for MediaConvert. What mistakes am I doing in the code or in the decryption settings?
import os
import base64
import boto3
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
# Initialize AWS KMS client
#session = boto3.Session(profile_name='your_profile_name') # Replace with your AWS profile
#kms_client = session.client('kms')
kms_client = boto3.client('kms', region_name='us-east-1')
# Function to generate a random initialization vector (IV)
def generate_iv():
return os.urandom(16)
# Function to pad the plaintext to a multiple of block size
def pad_data(data, block_size):
padder = padding.PKCS7(block_size * 8).padder()
padded_data = padder.update(data) + padder.finalize()
return padded_data
# Function to encrypt a file using AES-CBC
def encrypt_file(filename, key):
with open(filename, 'rb') as file:
plaintext = file.read()
iv = generate_iv()
base64_iv = base64.b64encode(iv)
print("the iv : ", iv)
print("the iV in base 64 : ", base64_iv)
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
encryptor = cipher.encryptor()
padded_plaintext = pad_data(plaintext, algorithms.AES.block_size)
ciphertext = encryptor.update(padded_plaintext) + encryptor.finalize()
base64_encoded_encrypted_data_key = base64.b64encode(ciphertext).decode('utf-8')
# print("the encrypted data key ", base64_encoded_encrypted_data_key)
with open('encrypted_'+filename, 'wb') as file:
file.write(iv)
file.write(ciphertext)
# Replace 'your_profile_name' with your AWS profile and 'your_key_alias' with your KMS key alias
profile_name = 'default'
#key_alias = 'your_key_alias'
# Replace 'video.mp4' with the name of your video file
filename = 'video.mp4'
# Get data key from AWS KMS
kms_response = kms_client.generate_data_key(
KeyId= <<kms-keyid>>,
KeySpec='AES_256'
)
data_key = kms_response['Plaintext']
base64_encoded_encrypted_data_key = base64.b64encode(data_key).decode('utf-8')
print("datakey = ", base64_encoded_encrypted_data_key)
encrypt_file(filename, data_key)
print('Encryption completed.')
The decryption settings in MediaConvert:
This is the error:

