Skip to content

Encrypt and auto mount a secondary disk

Preparations

Make sure you have the correct name of your drive and make sure there's no important data on is since the drive will be wiped.

You can find the disk you want to encrypt with lsblk or in the application called Disks (gnome-disks)
In this case we are going with /dev/sdb.

If your disk doesn't already have a partition you need to create one.
WARNING - any data on the disk will be lost.

Find the UUID of your drive and save this UUID for later.

sudo blkid /dev/sdb1

Format and encrypt the disk

Run fdisk.

sudo fdisk /dev/sdb
Press n
If you want the defaults just press enter through the guide, write the changes with w.

Encrypt the partition and pick a super long passphrase - store it in your password manager.
You will be able to access your encrypted disk from another PC with this passphrase.

sudo cryptsetup -y -v luksFormat /dev/sdb1

Create the mapping (replace "secure_disk" with whatever mapping name your want).

sudo cryptsetup luksOpen /dev/sdg1 secure_disk

Format the partition.

sudo mkfs.ext4 /dev/mapper/secure_disk -L "Secure disk"

Create a mount point for your drive.

sudo mkdir -p /mnt/secure_disk
Set permissions for the drive.
sudo chown $USER:$USER /mnt/secure_disk

Create the key file.

sudo dd if=/dev/urandom of=/etc/crypt_sdb1.keyfile count=1 bs=512

Set permissions on the file.

sudo chmod -rw /etc/crypt_sdb1.keyfile

Add the key file.

sudo cryptsetup luksAddKey /dev/sdb1 /etc/crypt_sdb1.keyfile

Add it to crypttab.

sudo nano /etc/crypttab

Replace x with your UUID received earlier.
secure_disk UUID=x /etc/crypt_sdb1.keyfile luks,discard

Auto mount

sudo nano /etc/fstab
Add this to the end of the file /dev/mapper/secure_disk /mnt/secure_disk ext4 defaults 0 2

Backup LUKS headers

It's always a good idea to backup your LUKS headers.

sudo cryptsetup luksHeaderBackup --header-backup-file ~/backup/luks-headers/sdb1 /dev/sdb1

Restore LUKS headers

If you ever need to restore them.

sudo cryptsetup luksHeaderRestore --header-backup-file ~/backup/backup/luks-headers/sdb1 /dev/sdb1