-
-
Save wenhuizhang/165e0d16b094266b7f0218c23c5cb5ed to your computer and use it in GitHub Desktop.
Encrypt existing partitions with LUKS2 on Ubuntu 20.04
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment