Generating the passphrase (Keyfile)
We need to generate the password or keyfile that can unlock your LUKS partition, this “password” will then be a way to unlock your LUKS partition. To create it we can use the following command.
dd if=/dev/random bs=32 count=1 of=/pathto/keyfile
You then need to create a LUKS partition using GUI, or using command line with the following commands :
Find the partition you want to encrypt
Then we need to use an utility that is already install on most of Linux distributions (cryptsetup) and use it to encrypt our partition with our keyfile.
cryptsetup luksFormat partition /pathto/keyfile
When it’s done, you should be able to open your encrypted partition using the same utility. In this example DEV is your LUKS partition, MAPPING a name you want to give to the LUKS mapping (That can be anything).
cryptsetup luksOpen DEV MAPPING --key-file /pathto/keyfile
Then you can close it.
cryptsetup luksClose MAPPING
Now that we checked that our partition encryption works and our keyfile too, we can plug the USB drive we want to use and copy the keyfile to it.
cp /pathto/keyfile /pathtousbdrive/keyfile
We’re almost done, now we need to specify that we want to unlock our partition automatically when the USB is connected in the crypttab configuration file.
And add a line that will vary depending of your configuration
MAPPING UUID=UUIDofyourLUKSpartition /pathtousbdrive/keyfile luks,nofail
There you go, the last step is to regenerate the initramfs image of your system to apply these changes, to do that use the following commands depending of your system.
If you want to be safe you can also backup the current initramfs you are using.
cp /boot/initramfs-$(uname -r).img /boot/initramfs-$(uname -r).bak.$(date +%m-%d-%H%M%S).img
Then update the initramfs
On debian-based systems :
update-initramfs -k all -u
On Red Hat :
dracut -f -v