How to create and use LUKS encrypted partition in Linux

It is easy to create a LUKS container and a partition within it, using the GUI on Linux. The application that enables this easily is the gnome-disk-utility. However, if you want to use the command line to set up a LUKS encrypted device, read on.

Exercise appropriate caution before doing any of the below with appropriate safeguards as they can result in permanent data loss

Before setting up a LUKS encryption on the hard drive open a terminal window and check partitions using:
$ sudo df <enter>
$ cat /proc/partitions <enter>

To get a list of hard disk devices, use:
$ sudo fdisk -l <enter>

To create a LUKS container, open a terminal window and enter the following command (in my case the device was a USB drive at /dev/sdb1):
$ sudo cryptsetup -y -v --type luks2 luksFormat /dev/sdb1 <enter>

To open the LUKS container:
$ sudo cryptsetup luksOpen /dev/sdb backup1 <enter>
To check it’s status:
$ sudo cryptsetup -v status backup1 <enter>

To fill the the partition with zeroes. Note this takes a very long time depending on the size of the disk
$ sudo dd if=/dev/zero of=/dev/mapper/backup1 bs=100M status=progress <enter>

To create a ext4 partition within the LUKS container:
$ sudo mkfs.ext4 /dev/mapper/backup1 <enter>

To mount and check it:
$ sudo mount /dev/mapper/backup1 /media/user1/backup1 <enter>
$ sudo df -H <enter>
$ sudo cd /media/user1/backup1 <enter>
$ ls -la <enter>
$ sudo cd ~ <enter>
$ sudo umount /media/user1/backup1 <enter>

Finally, close the volume:
$ sudo cryptsetup luksClose backup1 <enter>

The drive can now be disconnected.

To change encrypted partition container password:
$ sudo cryptsetup luksDump /dev/sdb1 <enter>
$ sudo cryptsetup luksAddKey /dev/sdb1 <enter>

Enter the passphrase.

To remove or delete the old password and you need to enter the old password to do it
$ sudo cryptsetup luksRemoveKey /dev/sdb1 <enter>

Up to 8 passwords can be setup for the volume.