Skip to content

Instantly share code, notes, and snippets.

@krzys-h
Last active February 24, 2024 22:26
Show Gist options
  • Save krzys-h/226a16eb56c82df0dc3a9d35fad989c8 to your computer and use it in GitHub Desktop.
Save krzys-h/226a16eb56c82df0dc3a9d35fad989c8 to your computer and use it in GitHub Desktop.
Encrypt existing partitions with LUKS2 on Ubuntu 20.04
#!/bin/bash
# Encrypt an existing partition with LUKS2 on Ubuntu 20.04 LTS
# DISCLAIMER: USE AT YOUR OWN RISK AND MAKE BACKUPS
# Made for my personal use and has almost NO error checking!!
# Based on instructions from:
# https://wiki.archlinux.org/index.php/dm-crypt/Device_encryption#Encrypt_an_existing_unencrypted_filesystem
DISK="$1"
if [ -z "$DISK" ]; then
echo "Usage: $0 /dev/sdXY"
exit 1
fi
# Run a filesystem check
e2fsck -f "$DISK"
# Make the filesystem slightly smaller to make space for the LUKS header
BLOCK_SIZE=`dumpe2fs -h $DISK | grep "Block size" | cut -d ':' -f 2 | tr -d ' '`
BLOCK_COUNT=`dumpe2fs -h $DISK | grep "Block count" | cut -d ':' -f 2 | tr -d ' '`
SPACE_TO_FREE=$((1024 * 1024 * 32)) # 16MB should be enough, but add a safety margin
NEW_BLOCK_COUNT=$(($BLOCK_COUNT - $SPACE_TO_FREE / $BLOCK_SIZE))
resize2fs -p "$DISK" "$NEW_BLOCK_COUNT"
# Run the encryption process
cryptsetup reencrypt --encrypt --reduce-device-size 16M "$DISK"
# Resize the filesystem to fill up the remaining space (i.e. remove the safety margin from earlier)
cryptsetup open "$DISK" recrypt
resize2fs /dev/mapper/recrypt
cryptsetup close recrypt
# Don't forget to update /etc/crypttab and /etc/fstab if required!
#
# For example:
# /etc/crypttab
# crypt_root UUID=xxx none luks,keyscript=decrypt_keyctl
# crypt_home UUID=xxx none luks,keyscript=decrypt_keyctl
# /etc/fstab
# /dev/mapper/crypt_root / ext4 errors=remount-ro 0 1
# /dev/mapper/crypt_home /home ext4 defaults 0 2
#
# The decrypt_keyctl makes it possible to unlock both partitions with the same password,
# and unlock gnome-keyring-daemon if you enable autologin and it's encrypted with the same password
# Note: if you are doing a clean install, using LVM is probably a better idea
#
# and remember to run "update-initramfs -u -k all" after updating the rootfs crypttab
@tk425
Copy link

tk425 commented May 13, 2022

worked like a champ on Ubuntu 22.04 - thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment