In order to use LUKS to encrypt a filesystem that is contained in a file, you actually have to follow the same steps as when encrypting a physical partition, plus two. These include:

So, let’s create the file. The following command creates an 100MB file, named "container1", which is full of random data:

dd if=/dev/urandom of=container1 bs=1024 count=100000

To create a mapping between this file and a free loop device, we’ll use losetup (part of util-linux). Check which loop device is free in your system with the command:

losetup -f

For me it was /dev/loop0. So, I map the "container1" file to /dev/loop0. As root:

# losetup /dev/loop0 /path/to/container1

From now on, the steps are exactly the same as before. We just use /dev/loop0 instead of the ZIP disk:

# cryptsetup --verbose --cipher "aes-cbc-essiv:sha256" --key-size 256 --verify-passphrase luksFormat /dev/loop0
# cryptsetup luksOpen /dev/loop0 encr-container1
# mkfs.ext3 /dev/mapper/encr-container1
# mount -t ext3 -o rw,defaults /dev/mapper/encr-container1 /mnt/tmp/

We can now copy some files to our encrypted partition, like on a regular disk partition. We unmount it and delete the device mappings with the following commands:

# umount /mnt/tmp/
# cryptsetup luksClose encr-container1
# losetup -d /dev/loop0

So, to mount a LUKS encrypted filesystem within a file you need to create two device mappings before you mount it for use. Of course some automation can be achieved using scripts, but you will still have to supply the passphrase in order to use the encrypted partitions.

Originally published: Here