Create an encrypted container in Linux
Posted on 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:
First you create a file with a specific size, e.g.
CONTAINER
with a size of 1GB:fallocate is used to preallocate blocks to a file.
Initialize a LUKS partition using the
CONTAINER
-fileYou will be asked to give a encryption key, which is later used to decrypt the container. Alternatively you may also use a
key-file
The content of the key-file contains the passphrase.
Decrypt (opens) the container file and creates a mapping as
/dev/mapper/container
or
The entries in
/dev/mapper
are LVM logical volumes1The content of the key-file contains the passphrase.
Format the file, for example
ext4
Opening and mounting the container
Now you can mount the container file to be used for accessing (reading, copying, …) content to it:
Open (decrypt) the container
or
Mount it to a mount point e.g.
/mnt/container
- assuming the folder exists already
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
Un-mount container
Close the container