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)
- Open the Terminal. Yep. Most of the commands are prefixed with sudo.
- 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.
- 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
- Open the container. It has no filesystem currently, so we can't store anything yet
cryptsetup luksOpen ~/container.store encrypted --key-file ~/keyfile
- The file will be mounted under /dev/mapper/encrypted
- 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
- After the container is mounted, your regular user does not have the necessary permissions to create files or delete anything. This can be solved by:
cd ~/Private chown $USER:$USER .
Now you should be able to create, modify or delete files in the container.
How to unmount the container
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.