Encrypted filesystems, loop devices, cryptsetup
The GNU Privacy Guard is a common tool for encrypting files. An alternative approach for encrypting file hierarchies involves encrypting entire filesystems.
Encrypting whole hierarchies of files typically means tarring them up and encrypting the tarball, which quickly becomes cumbersome. A more natural approach would be altogether encrypting filesystem files.
1 Procedure
This is loosely based on a recipe suggested in the Debian reference. We're supposed to use a command called cryptsetup to cover the basic operations. This command normally only deals with devices, not regular files. A workaround is to associate a loop device with a regular file.
Start by creating a file to hold the filesystem. You may want to use
/dev/urandomas input file as shown here:I also once gavedd if=/dev/urandom of=secrets bs=1M count=4/dev/randoma spin, as suggested in some Debian README file, but I couldn't get the filesystem size I wanted and it was impossibly slow.Map a loop device to the file for
cryptsetupto use withlosetup, as shown here:You can check if it worked withlosetup /dev/loop0 secretslosetup -a. If you happen to get an error looking likeioctl: LOOP_SET_FD: Device or resource busybut the loop device doesn't look busy, it may be because a kernel module still has a grab on it (e.g. if you've previously been playing around withcryptoloop).Initialise the LUKS partition with this command, which will ask for a passphrase.
cryptsetup luksFormat /dev/loop0Map the newly-initialised LUKS partition to a device which should encouragingly show up as
/dev/mapper/secrets. You'll be asked for the passphrase you just supplied:cryptsetup luksOpen /dev/loop0 secretsYou may now treat the mapped device as pretty much any block device and, for instance, write any filesystem of your liking to it. For instance, write an ext2 filesystem, which is suitably compact for small block devices:
Likewise, you may want to try and mount it to check that everything is fine. Now may also be a good time to change ownership of the root directory.mkfs.ext2 /dev/mapper/secrets mount /dev/mapper/secrets mpOnce you are done, you should of course unmount the filesystem:
umount mp cryptsetup luksClose secrets losetup -d /dev/loop0You may then remove the device mapping and detach the file mapped with the loop device.
