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/crontab

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

Was this post helpful?

Geef een reactie

Het e-mailadres wordt niet gepubliceerd. Vereiste velden zijn gemarkeerd met *

Deze website gebruikt Akismet om spam te verminderen. Bekijk hoe je reactie-gegevens worden verwerkt.