Here are some instructions on how to create an encrypted filesystem on a file.
Create an empty file with the size of your container. Here I’ll
use a 100MB container. The file is created with
which reads chunks from an input device and writes the contents
to a file or another device.
dd if=/dev/zero bs=1M count=100 of=~/my-container.img
This command means the following: read 100 chunks of one megabyte
from the zero device
write them to the file
~/my-container.img. This will
create a file named
my-container.img in your home
directory that will be about 100MB of zeros.
Next, we’ll initialise the LUKS partition on the file and set the initial passphrase.
sudo cryptsetup luksFormat ~/mycontainer
Note that you need to type “YES” (i.e. ‘yes’ in uppercase to confirm the operation; there is no error message when you fail this step which may be confusing. Make sure that the file you want to format is your container file or an empty partition’s device file. Input your passphrase when prompted. You will have to input this passphrase whenever you mount the container unless you decide to store the passphrase with the container (which obviously is not very safe). Note that you have to run this as root, because cryptsetup must access the loopback device. (On the Hurd this would not be necessary, I think.)
Now, we’ll open the container. Opening the container creates a kernel device file which can then be mounted.
sudo cryptsetup luksOpen ~/mycontainer secret-device
This command will prompt for the container’s passphrase and then
create a device file with the name
/dev/mapper/secret-device. You may choose another name than
The container is now decrypted. Since the device has no
filesystem yet we still cannot put any data on it. Use
mkfs.ext4 to create an ext4 filesystem on the decrypted
sudo mkfs.ext4 /dev/mapper/secret-device
Now the filesystem can be mounted like a filesystem on a regular block device.
mkdir ~/my-mount-point sudo mount /dev/mapper/secret-device ~/my-mount-point
The first command creates a new mount point (an empty directory) named “my-mount-point” in your home directory. The second command mounts the decrypted device at this location.
You can now write to the directory as usual. Once you are done follow these steps to unmount the device and close (= re-encrypt) the container:
sudo umount ~/my-mount-point sudo cryptsetup luksClose secret-device
To access the container again only these two commands are required:
sudo cryptsetup luksOpen ~/mycontainer secret-device sudo mount /dev/mapper/secret-device ~/my-mount-point
You could use
/dev/random as the input device if
you wanted to, but that would be considerably slower and
wouldn’t help you much. Later commands will initialise
the file/partition, so you don’t need to initialise it
manually with random numbers.