Thomas' Tech Tips

How to create encrypted LUKS volume in a file

29 March 2023 - Thomas Damgaard

LUKS can be used for whole disk encryption on Linux. But it can also be used to encrypt a volume stored in a file on a filesystem.

Here is how to do it: First create a file that will contain the LUKS volume. We fill it with random bytes.

dd if=/dev/urandom of=myvol.luks.dat bs=1M count=2k status=progress

$ sudo cryptsetup luksFormat --pbkdf argon2id  myvol.luks.dat

WARNING!
========
This will overwrite data on myvol.luks.dat irrevocably.

Are you sure? (Type uppercase yes): YES
Enter passphrase for myvol.luks.dat:
Verify passphrase:

Now, open the volume.

$ sudo cryptsetup luksOpen myvol.luks.dat myvol

Now that the volume is opened, create a file system on it:

$ sudo mkfs.ext4 -v -m0 /dev/mapper/myvol
mke2fs 1.44.5 (15-Dec-2018)
fs_types for mke2fs.conf resolution: 'ext4'
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
Stride=0 blocks, Stripe width=0 blocks
64512 inodes, 258048 blocks
0 blocks (0.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=264241152
8 block groups
32768 blocks per group, 32768 fragments per group
8064 inodes per group
Filesystem UUID: 78b1882e-0f4b-486e-a706-8374ad8a3db9
Superblock backups stored on blocks: 
        32768, 98304, 163840, 229376

Allocating group tables: done                            
Writing inode tables: done                            
Creating journal (4096 blocks): done
Writing superblocks and filesystem accounting information: done

Mount the newly created file system

$ sudo mount /dev/mapper/myvol /mnt

Now the encrypted LUKS volume is mounted in /mnt. Do what you need to do. Copy files and folders over, etc.

Then when you are done, unmount the volme:

$ sudo umount /mnt

Next time you need to access data in the encrypted volume, just run $ sudo cryptsetup luksOpen myvolume.luks.dat myvol to unlock the volume and $ sudo mount /dev/mapper/myvol /mnt to mount the volume.

Filed under: howto, linux, luks, security, tips

Back to article list