Encrypting in-place is possible, but dangerous. It's easier by far to just wipe / format / mkfs it, and repopulate it with files from elsewhere.
For the in-place approach, first you have to shrink the filesystem by at least 2MiB
to make room for the LUKS header at the beginning of the drive. For safety, shrink it a bit more than that.
Then you have to keep in mind that due to the LUKS header, all data on the encrypted container has at least a 2MiB
offset. Thus, a linear dd
copy of the unencrypted to the encrypted container will not work, as each write would overwrite data that has not been read yet.
To avoid that, the copy operation has to run backwards. There is no direct support for that in dd
, but you can emulate it using seek=$x skip=$x count=1
in a backwards loop that decrements $x
by one in each step until $x=0
.
Example using device /dev/sdx1
with ext4
filesystem:
# make sure it's not mounted anywhere
umount /dev/sdx1
# backup the first 128MiB somewhere
dd bs=1M if=/dev/sdx1 of=/somewhere/sdx9.backup count=128
# shrink filesystem by 128MiB
resize2fs /dev/sdx1 $(($(blockdev --getsize64 /dev/sdx1)/1024/1024-128))M
# create encryption layer
cryptsetup luksFormat /dev/sdx1
cryptsetup luksOpen /dev/sdx1 luksx1
# dd backwards using GiBs of memory. Change math and bs for less memory usage.
for x in $(seq $(($(blockdev --getsize64 /dev/sdx1)/1024/1024/1024+1)) -1 0)
do
dd bs=1G iflag=fullblock seek=$x skip=$x count=1 \
if=/dev/sdx1 of=/dev/mapper/luksx1
done
# include backup for region previously overwritten by LUKS header
dd bs=1M if=/somewhere/sdx9.backup of=/dev/mapper/luksx1
# grow filesystem to full size
resize2fs /dev/mapper/luksx1
Before doing this, test the procedure with a temporary device first.
If the procedure is cancelled at any point, it's pretty much a lost cause, since you end up with a half-encrypted thing.
There are frontends that pretty much use the same method. cryptsetup
itself has a reencrypt-program, or you could try your luck with http://www.johannes-bauer.com/linux/luksipc/ . I prefer the manual approach simply because I understand how it works and what can go wrong.