Encrypt a file image in Linux

Problem

I want to create a ciphered file partition mounted on loopback.

Create crypto image

1. First create the file image which will contain all your encrypted data:

dd if=/dev/zero of=extra.img bs=100k count=1024

2. Load the cryptoloop kernel module:

sudo modprobe cryptoloop

3. Set up the loop device with your desired encryption algorithm. It will ask you for the password:

sudo losetup -e aes /dev/loop0 extra.img

4. Format the file partition and mount it:

mkfs.ext4 /dev/loop0
sudo mount /dev/loop0 /mnt/

Load the data partition

The next time you want to load the partition you have to repeat this steps:

sudo modprobe cryptoloop
sudo losetup -e aes /dev/loop0 extra.img
sudo mount /dev/loop0 /mnt/

Ubutu/Debian Users: By default, Debian systems run the password through a hash function. So if you have created your image in another distribution and want to load in Debian you have to add the “-N” option:

sudo losetup -e aes -N /dev/loop0 extra.img

Unload the data partition

To umount the partition:

sudo umount /dev/loop0
sudo losetup -d /dev/loop0

Leave a comment