An Encrypted Loop Device to Store Sensitive Data

As I mentioned elsewhere, I decided to try using an encrypted loop device to store some of my sensitive files. The first thing I had to do was to create the file that would be mounted later. The most efficient way I could find to do that was to create a sparse file--one which has a set size marked out for it, but which can actually be smaller on disk. (Think of a file which can grow/shrink as needed up to a set limit.)

dd if=/dev/zero of=container_file bs=1 count=0 seek=1G

The important part of the above command is the "seek" statement, which tells dd to make the file sparse. I used 1G for the file size simply because it was roughly double the size of the sensitive files I wanted to store.

The next thing to do was to mount the loop device, set it up as encrypted, and then format it. To do that, I typed:

sudo losetup /dev/loop0 container_file sudo cryptsetup luksFormat /dev/loop0

I entered my password--twice--and the encrypted part was done. Then it was time to format the device:

sudo cryptsetup luksOpen /dev/loop0 container_file sudo mkfs.ext4 /dev/mapper/container_file

Then I mounted my new device:

sudo mount /dev/mapper/container_file ${HOME}/secrets

I changed directory to ~/secrets, copied all my sensitive files into it and I was done.

Of course, I had to now test the system. I reversed the process of mounting my loop device:

sudo umount ~/secrets sudo cryptsetup luksClose /dev/mapper/container_file sudo losetup -d /dev/loop0

Then I checked the filesize using both du and ls and got the following results:

du -h container_file: 504M ls -al container_file: 1G

It seemed to me at that point the setup was working as planned. I created a pair of shell scripts to mount and unmount the loop device, and will test the system for a couple of weeks to see if it continues to work well. The one wrinkle I've encountered since going to this new system has been in the copying of the unmounted sparse file, which requires letting rsync/cpio/tar/cp know through an option on the command line. Otherwise, the programs will copy over the set (rather than the actual) file size, which defeats the whole purpose of having a sparse file. I've already modified my backup scripts appropriately.

~~~~~~~~~~~~~~~~~~~~~~~~~

~thumos thumos [at] tilde [dot] club March 2025