Create an encrypted container in linux

In case you have some files which you want to have encrypted in a secured container, like a password-ed zip file. When mapping this container file you have to enter a password or you can use a key file to unlock the file! I will use a manual password entry to unlock the container.

Installing cryptsetup

Use yum, apt to install cryptsetup or download the source to build your own. For now I will use apt as an example.

# apt-get install cryptsetup

Creating the container file

Create a 1GB file named ‘PRIVATE’

# fallocate -l 1GB PRIVATE

Set the file as luks

# cryptsetup -v luksFormat PRIVATE

Decrypt the file and create /dev/mapper/private_file

# cryptsetup -v luksOpen PRIVATE private_file

Format private file as ext4

# mkfs -t ext4 /dev/mapper/private_file

Mounting and unmounting the container file

Make sure the file is decrypted:

# cryptsetup -v luksOpen PRIVATE private_file

Mount the private_file

# mkdir /mnt/private_file
# mount /dev/mapper/private_file /mnt/private_file

Umount and close file

# umount /mnt/private_file
# cryptsetup luksClose private_file

Mounting automatically with a key-file or online key

You can auto mount your encrypted container by creating a key-file.
In this case I will use the string “MyRandomString123” as an example. Better is to use a random pwgen string of 64 characters!

# cryptsetup luksAddKey /dev/sdX MyRandomString123 

Or when you want to create a file with random a random string

# pwgen -s 64 1 > MyKeyFile
# cryptsetup luksAddKey PRIVATE ./MyKeyFile

Place this keyfile somewhere on your filesystem (ea /root) or online page and open it up!

cat /root/MyKeyFile | cryptsetup -v luksOpen PRIVATE private_file

Or from online

 curl -s https://my_site.tld/MyKeyFile | cryptsetup -v luksOpen PRIVATE private_file 

Or open it using fstab so it opens on reboot.
Add to /etc/crypttab

private_file /root/PRIVATE /root/MyKeyFile luks 

And add to /etc/fstab

/dev/mapper/private_file /mnt/private_file ext4 defaults 0 2

2 thoughts on “Create an encrypted container in linux

  1. Hi, thanks for this quick and useful tutorial! I just wanted to let you know that you probably meant to write “And add to /etc/fstab”, not “And add to /etc/crontab” as the last step.

Leave a Reply

Your email address will not be published. Required fields are marked *