Saturday, December 24, 2016

How to create an encrypted file container with cryptsetup in Linux

Hi all,

In this post I will tell you how to create an encrypted file container of 1 GB using cryptsetup (LUKS), where you can store your sensitive files and nobody else can access it without a password. Of course, you may also create an entire encrypted disk, but that's another story and we will leave it for the next time. All commands from this article were tested in Debian Jessie, but should also work in Ubuntu and in other distros with few modifications. So let's get started.

Part 1 - required only once


1. Update and install cryptsetup
sudo apt-get update
sudo apt-get install cryptsetup

2. Create an empty file container of 1 GB (or any other size that you wish), which can be located, for example, in home directory:
dd if=/dev/zero of=file_container bs=1M count=1024

3. Format empty container as LUKS (Linux unified key system):
sudo cryptsetup luksFormat file_container

4. Open LUKS container using desired device name (which is 'crypt1' in our case):
sudo cryptsetup luksOpen file_container crypt1

5. Format an encrypted file container with some file system (eg. ext4):
sudo mkfs.ext4 -j /dev/mapper/crypt1

6. Create mount point directory and mount an encrypted container right there:
mkdir decrypted
sudo mount /dev/mapper/crypt1 decrypted

Now you can access your private files which are in the decrypted directory.

7. Close encrypted container so that nobody can access your decrypted data:
sudo umount /dev/mapper/crypt1
sudo luksClose crypt1

Part 2 - usage on a daily basis


1. Open LUKS
sudo cryptsetup luksOpen file_container crypt1

2. Mount into a folder:
sudo mount /dev/mapper/crypt1 decrypted

3. Close it when you no longer need to access your data:
sudo umount /dev/mapper/crypt1
sudo luksClose crypt1

Part 3 - handy scripts


Create file 'open.sh' with the following content:
sudo cryptsetup luksOpen file_container crypt1
sudo mount /dev/mapper/crypt1 decrypted

and also file 'close.sh':
sudo umount /dev/mapper/crypt1
sudo luksClose crypt1

Change mode to allow to execute files:
chmod +x open.sh
chmod +x close.sh

Now you can easily run ./open.sh, then access your private data. When you're done working with your files, simply close it by running ./close.sh.

That's it. Hope this was useful to you.


No comments:

Post a Comment