Encrypt partition with dm-crypt

Ever wnated to have your external disk or USB stick encrypted? This is a way to get there on a Debian-based system using dm-crypt and LUKS.

First, make sure dm-crypt module is loaded (see if /dev/mapper/ is present), and if not, load the module:

modprobe dm-crypt

Now you can use cryptsetup to encrypt your device (you’ll be asked for a password):

cryptsetup --verbose --key-size 256 --verify-passphrase luksFormat /dev/sdb1

After this step, you can open the encrypted disk.

cryptsetup luksOpen /dev/sdb1 mydisk

The disk is not ready yet, we need to format it first, just as if we connected an empty device. In theis example, I’ll format it using ext3 file system.

mkfs.ext3 -j -m 1 -O dir_index,filetype /dev/mapper/mydisk

Now you can finally mount and access your disk.

mount -t ext3 /dev/mapper/mydisk /media/mydisk

When you’re done and want to unplug the device, you unmount it the usual way:

umount /dev/mapper/mydisk

and then use LUKS to close the encrypted connection:

 cryptsetup luksClose mydisk

Now you can remove the device.