Creating a LUKS-encrypted Partition with Linux

LUKS is probably the best (easiest to use and fairly secure) option for encrypted disk partitions under Linux. Here's a rote method to turn a raw partition into a LUKS-encrypted ext4 partition (I'm reading up on the details over time):

# cryptsetup --verify-passphrase --key-size 256 luksFormat /dev/sdx1
# cryptsetup luksOpen /dev/sdx1 <part-name>
# mke2fs -j -L <part-name> -m 2 -t ext4 /dev/mapper/<part-name>

Where "/dev/sdx1" is the partition you want to encrypt, and "<part-name>" is replaced with the actual name/label you want the partition to have. As always with modifying disk partitions, be very, very sure you've selected the right one. You'll be asked for the passphrase (twice) after the first command, and once after the second.

Options to mke2fs:

  • -j - create an ext3 journal (probably unnecessary with "-t" below)
  • -L - give the volume a label
  • -m - reserved-blocks-percentage for super-user, which means the lost+found folder. It also means "space the user can't practically use," and on Terabyte-sized hard drives, the default 5% isn't really necessary any more
  • -t - specify the file system type

The following will now work (assuming the mount point in /media/ exists, create it if you need to):

# mount /dev/mapper/<part-name> /media/<part-name>

Another option would be to disconnect the drive and reconnect it, letting automount do its job. Or, if you live without automount as I do, you can do this:

# blkid
/dev/sdx1: UUID="8e68c7a-fba0be-087f-aafb861b4" TYPE="crypto_LUKS"

blkid should be run as root. Mounting the partition can (and probably should) be done as a user:

$ pmount sdx1 <part-name>

I don't think pmount is installed by default on most distros, but if you don't have automount for some reason, it's the best solution I've found - even if it is a bit quirky.

Here's an ugly little loop I've incorporated into my backup routine:

for part in $(ls /dev/mapper)
    # there are usually a couple duds in there, but it does get the important ones:
    cryptsetup luksHeaderBackup --header-backup-file ${backupdir}/${part}.header.${datestamp}.bin /dev/${part%_crypt}

The HOWTO warns that the commonest problem with LUKS is corruption or loss of the LUKS header. Read it for more detail on what's going on. Note that I've never had to restore the LUKS header from this (I just started doing it).