Creating encrypted containers in Linux

by Felix Kinaro About 2 min reading time

Creating encrypted containers in Linux using cryptsetup

Cryptsetup is a commandline utility for encrypting storage devices and volumes.
LUKS is the Linux Unified Key System.

In this guide, we are going to create an encrypted LUKS2 container to store sensitive documents (Or any info you may wish to keep private)

Steps followed

  1. Open the Terminal. Yep. Most of the commands are prefixed with sudo.
  2. Next, we create a file which we are going to format as a container.
dd if=/dev/zero of=~/container.store bs=1 count=0 seek=4G

Now we have a 4GB container that we need to encrypt and mount. You can use a keyfile to unlock your container or a password. A keyfile is more secure since it provides a higher entropy than a password. But then the question of safe storage arises.

  1. Now we generate a keyfile to encrypt our container. If you lose the keyfile then you can kiss your data goodbye
dd if=/dev/urandom of=~/keyfile bs=1024 count=8

Here we generate an 8KiB keyfile. 1KiB should suffice, but lets go with 8.
4. The next thing is to format the 4GB file as a container and mount it.

cryptsetup luksFormat --type luks2 ~/container.store ~/keyfile
  1. Open the container. It has no filesystem currently, so we can't store anything yet
cryptsetup luksOpen ~/container.store encrypted --key-file ~/keyfile
  1. Next we format the container with a filesystem of our choice. Here I go with btrFS
mkfs.btrfs /dev/mapper/encrypted -L Private

The filesystem created is given a label of Private
7. Mount the newly created filesystem if it isn't automatically mounted already.

mkdir ~/Private
mount /dev/mapper/encrypted ~/Private

Now our container is mounted at ~/home/$USER/Private

cd ~/Private
chown $USER:$USER .

Now you should be able to create, modify or delete files in the container.

How to unmount the container

  1. Run:
sudo umount ~/Private

Enter your password when prompted
2. Close the LUKS device

sudo cryptsetup luksClose /dev/mapper/encrypted

Congratulations!! Now you are good to go.

Subscribe to receive weekly articles

Your data is handled by Buttondown.