On GNU/Linux systems, LUKS can be used to encrypt storage devices like USB sticks, hard drives, SSDs and more. But it is also possible to create ISO image files, encrypt them and mount them when necessary.

Table of contents

First time creation and mount

First of all, a size is required. It is not possible to resize images after encrypting them. So if such an image has 1 GB of size but contains only a 1 KB text file, the size will still be 1 GB. For this article, I will create a 1 GB image.

Also, a name is required. I will use “testimage”.

The first step is to create a file with the required size. In this case, 1 GB.

$ touch testimage
$ dd if=/dev/urandom of=testimage bs=1M count=1024

If the image needs to be bigger or smaller, the count parameter has to be changed accordingly to the size in MB.

Next, the image needs to be encrypted. I will use AES encryption.

$ cryptsetup -c aes-xts-plain64 -s 512 -h sha512 luksFormat testimage

This step first needs to be confirmed by typing uppercase YES and then define and confirm the passphrase for the image. Please note that the passphrase cannot be reset if forgotten. Forgetting the passphrase will result in rendering the encrypted files inaccessible.

This will overwrite data on testimage irrevocably.

Are you sure? (Type uppercase yes): YES
Enter passphrase: 
Verify passphrase: 

Now the image needs a file system. The default choice is ext4 since LUKA is almost exclusively used on Linux systems. This means, whatever machine is able to open the image, most probably is also able to use ext4 file systems.

To open the image, a name must be specified. This name will also appear under /dev/mapper as a device. If the image is called testimage, it will appear under /dev/mapper/testimage.

$ sudo cryptsetup luksOpen testimage testimage
$ sudo mkfs.ext4 /dev/mapper/testimage

The image is now open and formatted. It can be mounted like any USB stick or any other storage device.

$ mkdir ~/encrypted
$ sudo mount -t ext4 /dev/mapper/testimage ~/encrypted

To close the image, simply unmount the device and use luksClose

$ sudo umount /dev/mapper/testimage
$ sudo cryptsetup luksClose testimage

General usage of existing images

To re-mount an existing image, it needs to be opened and mounted.

$ mkdir ~/encrypted
$ sudo cryptsetup luksOpen testimage testimage
$ sudo mount -t ext4 /dev/mapper/testimage ~/encrypted

When done using the encrypted files, the image should be unmounted and closed again.

$ umount /dev/mapper/testimage
$ sudo cryptsetup luksClose testimage