Howto shrink a LUKS1/LUKS2 encrypted partition containing a ext4 filesystem
============================================================
-
Boot into live environment
-
Open your encrypted partition, e. g. /dev/sda7
sudo cryptsetup luksOpen /dev/sda7 crypt
-
Check ext4 filesystem for errors
sudo e2fsck -f /dev/mapper/crypt
-
(Temporarily) shrink ext4 filesystem to minimum size (recommended)
sudo resize2fs -pM /dev/mapper/crypt
.
You could also resize to a specific size, e. g. 6GiB x1024x1024x1024=6442450944Byte /512=12582912 sectors (blocks)
sudo resize2fs -p /dev/mapper/crypt 12582912s
Just make sure to resize to a smaller size than in step 8. -
Check ext4 filesystem for errors
sudo e2fsck -f /dev/mapper/crypt
-
Take note of the luks container header size (in sectors)
For 512 bit key length (e . g. for the default aes-xts-plain with 512 bit key) the LUKS1 header is 2 MiB. LUKS2 header is 4 MiB if created with cryptsetup < 2.1 or 16 MiB if created with cryptsetup ≥ 2.1.
sudo cryptsetup status crypt | grep offset
-
(Optional) Calculate the minimum luks volume size (in sectors)
7.1 Get the newly shrunken ext4 filesystem size (in Bytes)
sudo dumpe2fs -h /dev/mapper/crypt |& awk -F: '/Block count/{count=$2} /Block size/{size=$2} END{print count*size}'
7.2 Divide the above bytes by 512 to calculate the occupied sectors; e. g. 804773888 Byte /512 = 1571824 sectors
7.3 Add the luks header size from step 6. to 7.2; e. g. 1571824 + 32768 = 1604592 sectors [x512 /1024/1024/1024 =0.77GiB]
.
In this example, 1604592 sectors is the absolute minimum size you may choose to resize the luks volume to in the following steps! -
Resize luks container to e. g. 6GiB [x1024x1024x1024=6442450944Byte /512=12582912 sectors (blocks)]
sudo cryptsetup --size 12582912 resize crypt
-
Grow the temporarily shrunken ext4 filesystem to the maximum size the luks volume will now allow
sudo resize2fs -p /dev/mapper/crypt
and check
sudo e2fsck -f /dev/mapper/crypt
-
Close the luks volume
sudo cryptsetup luksClose crypt
-
Rewrite partition table
Note: We’ll assume /dev/sda7 is partition number 7
This step is potentially dangerous as we will delete your original luks partition and recreate it by writing new start and end sectors to the partition table. Please take care to use the correct values!
.
sudo parted /dev/sda
(parted) unit s
(parted) p
(parted) rm 7
.
We’ll now recreate this partition with the old START sector shown when you enteredp
(for example 21532672) and a new end sector.
.
New END sector = ~START sector~ + ~ext4 filesystem size from step 8~ + ~luks header size from step 6~
e. g. 34148352s = 21532672s + 12582912s + 32768s
(parted) mkpart primary 21532672s 34148352s
(parted) p
(parted) quit
-
Reboot!