Create an encrypted container in Linux

Posted May 5, 2021 by Adrian Wyssmann ‐ 2 min read

In case you have sensitive files which you want to additionally protect, you could add the to a zip file and encrypt the zip file. Or you might as well use an encrypted container

The advantage of having an encrypted container over a encrypted (zip)-file is, that you can mount it as a volume and easily access the files while you use them. Once done you close the container and would only be able to access it once you enter the decryption password. cryptsetup has you covered

cryptsetup is used to conveniently setup dm-crypt managed device-mapper mappings. For basic (plain) dm-crypt mappings, there are four operations.

To understand what we are doing, please also be aware of luks:

LUKS, Linux Unified Key Setup, is a standard for hard disk encryption. It standardizes a partition header, as well as the format of the bulk data. LUKS can manage multiple passwords, that can be revoked effectively and that are protected against dictionary attacks with PBKDF2.

You can find details to the specs in the official gitlab repo

Create the container file

Ensure you have cryptsetup installed, then you we can start:

  1. First you create a file with a specific size, e.g. CONTAINER with a size of 1GB:

    fallocate -l 1GB CONTAINER
    

    fallocate is used to preallocate blocks to a file.

  2. Initialize a LUKS partition using the CONTAINER-file

    cryptsetup -v luksFormat CONTAINER
    

    You will be asked to give a encryption key, which is later used to decrypt the container. Alternatively you may also use a key-file

    cryptsetup -v luksFormat CONTAINER --key-file ~/mykeyfile
    

    The content of the key-file contains the passphrase.

  3. Decrypt (opens) the container file and creates a mapping as /dev/mapper/container

    cryptsetup -v luksOpen CONTAINER container
    

    or

    cryptsetup -v luksFormat CONTAINER --key-file ~/mykeyfile
    

    The entries in /dev/mapper are LVM logical volumes1

    The content of the key-file contains the passphrase.

  4. Format the file, for example ext4

    mkfs -t ext4 /dev/mapper/container
    

Opening and mounting the container

Now you can mount the container file to be used for accessing (reading, copying, …) content to it:

  1. Open (decrypt) the container

    cryptsetup -v luksOpen CONTAINER container
    

    or

    cryptsetup -v luksFormat CONTAINER --key-file ~/mykeyfile
    
  2. Mount it to a mount point e.g. /mnt/container - assuming the folder exists already

    mount /dev/mapper/container /mnt/container
    

Closing and un-mounting

Once you are done, you have to close the container. Before you can do that, you need to un-mount it as otherwise the device will appear busy. SO

  1. Un-mount container

    umount /mnt/container
    
  2. Close the container

    cryptsetup luksClose container