A few days ago, I was preparing a key drive to unlock the encrypted partition on boot, the process of doing that manually is quite tedious, so I decided to write a script to automate the process.
/usr/local/libexec/script/makeKeyImg
#!/bin/dash
keyName=${1-key}.img
mkdir -p /tmp/sandbox/storage
cd /tmp/sandbox
dd if=/dev/zero of=$keyName bs=1M count=512
devLocation=$(losetup -Pf --show $keyName)
(echo n; echo p; echo 1; echo "\n"; echo "\n"; echo t; echo c; echo w) | fdisk $devLocation
mkfs.vfat ${devLocation}p1
mount ${devLocation}p1 storage
dd bs=512 count=4 if=/dev/random of=storage/key.bin iflag=fullblock
umount ${devLocation}p1
DEVUUID=$(blkid ${devLocation}p1 -s UUID | cut -d '"' -f 2)
losetup -d $devLocation
mv $keyName "${keyName%.*}-${DEVUUID}.${keyName##*.}"
/usr/local/bin/make-key-img
#!/bin/dash
doas /usr/local/libexec/script/makeKeyImg "$@"
If you use sudo
replace doas
with sudo
. Once you run the script it should create a image file with the key.bin
inside on a vfat
partition, the image file will be located in /tmp/sandbox
, the file name should be something
like key-ABCD-1234.img
(Yes, that the UUID after first hyphen) and run the following to write image to usb-storage.
dd if=key-ABCD-1234.img of=/dev/sdx bs=1M
Now the usb-storage device is ready for decrypting the partition, all you have to do is to configure luks to accept the key, there is already a tutorial on Arch Wiki on how to do that and can be found at https://wiki.archlinux.org/title/Dm-crypt/Device_encryption#Configuring_LUKS_to_make_use_of_the_keyfile
Tips
You can prevent the drive from being auto-mounted on boot up and on insert, just add the following line to /etc/fstab
quite easy.
UUID=ABCD-1234 /root/key vfat ro,noauto,umask=0377 0 0
The ro
means read-only, noauto
prevent auto-mounting and umask
restrict the permission making it read only for
root user and no access for other users and groups.
I also recommend making an encrypted backup copy of the image file.
Have fun 🤩