We stand with Palestine ❤️ Free Palestine 🇵🇸

No to genocide in Gaza. No to the killing of civilians. No to targeting hospitals and schools. No to deception and double standards.

Secure Your Data: How to Encrypt a Partition or Disk on Linux

How to Encrypt a Partition or Disk on Linux

While no method can guarantee 100% security for your data, encryption provides a highly reliable layer of protection, making it significantly more difficult for hackers and unauthorized users to access your private information. In this tutorial, we'll explore the best encryption solutions available for Linux users and walk you through the process of creating an encrypted partition step by step.

This article is sponsored by TUXEDOComputers, a German company that produces Linux hardware, notebooks, computers, and more. Always and forever, all ideas and opinions on this website are wholly mine, as my values are not for sale. To learn more, read our Code of Ethics.{alertInfo}

Disclosure: Please note that this article contains affiliate links and any sales made through such links will reward me a small commission – at no extra cost for you. These commissions help support the maintenance and growth of the blog, allowing me to continue providing quality content and resources.

{tocify} $title={Table of Contents}

LUKS or VeraCrypt?

Linux users have several options for file and directory encryption (Stacked filesystem encryption), but when it comes to encrypting entire disks or partitions (Block device encryption), two prominent and reliable solutions stand out: LUKS and VeraCrypt, both of which are open-source.

LUKS: The Standard

LUKS (Linux Unified Key Setup) is the standard specification for disk encryption on Linux, leveraging the dm-crypt subsystem in the Linux kernel for its cryptographic operations. When you choose encryption during the installation of your favorite Linux distribution, it’s typically based on LUKS unless specified otherwise.

Pros
  • Standardized and well-supported on Linux.
  • Multiple key slots for flexible key management.
  • Integrated with Linux distributions.
  • Secure and uses strong encryption algorithms.
  • Enhanced metadata management in LUKS2.
Cons
  • Performance overhead on low-end hardware.
  • Mostly managed via command line.
  • No support for hidden volumes.
  • Limited to Linux.

LUKS provides robust security by allowing multiple passwords (keys) to unlock the same encrypted partition. It also supports backup and restoration of the encryption header, a small block of metadata that includes information about the encryption algorithms (ciphers), type, and mode. Think of it as a gate with multiple key slots.

LUKS enables you to add and remove keys without reformatting (re-encrypting) the partition or disk. It uses PBKDF2 to strengthen passphrases, which involves hashing the password with a unique salt multiple times, making it much harder for attackers to crack. 

LUKS2, the updated version, introduces enhancements like support for advanced key derivation functions (KDFs) such as Argon2id, which offers improved resistance against password cracking, especially against GPU-powered attacks.

LUKS2 also features JSON-based metadata, making it easier to extend and parse, with better redundancy and multiple metadata copies to prevent data loss. While LUKS uses AES in XTS mode with a 512-bit key by default—providing high security and performance—it also supports other ciphers like Serpent, Twofish, and Camellia.

Thanks to Systemd-cryptsetup integration, LUKS works seamlessly with systemd, facilitating smooth management and access to encrypted block devices. Although LUKS lacks a graphical interface for encryption, many disk management tools, such as KDE's Disk Management, offer GUIs for creating encrypted disks or partitions on Linux.

LUKS is versatile, capable of encrypting any partition regardless of its filesystem. Whether you prefer the widely-used Ext4, the high-performance XFS, the feature-rich Btrfs, or even the Windows-centric NTFS, LUKS acts as a universal encrypter, ensuring your data remains private. However, due to potential compatibility issues and performance implications, encrypting an entire NTFS disk with LUKS is generally not recommended. Additionally, LUKS does not support cipher combinations or hidden volumes, which brings us to VeraCrypt.

VeraCrypt: The Contender

Derived from the discontinued TrueCrypt, VeraCrypt is a free and open-source encryption tool available on Linux, Windows, and macOS. Unlike LUKS, VeraCrypt offers a user-friendly graphical interface in addition to its console version, making it easy to encrypt and configure disks and partitions.

Pros
  • Cross-platform support (Windows, macOS, Linux).
  • User-friendly graphical interface.
  • Supports cipher combinations.
  • Hidden volumes for plausible deniability.
  • Can be used with a keyfile for added security.
Cons
  • Not as deeply integrated with Linux as LUKS.
  • May have slightly lower performance than LUKS.
  • Multiple passphrases not supported.
  • Does not officially support Argon2id

VeraCrypt allows you to create hidden volumes for plausible deniability, where one volume is concealed within another. It provides protection against data corruption or accidental overwrites of hidden volumes while they are mounted. However, this protection is not active when the hidden volume is unmounted.

A hidden volume is akin to a secret compartment within a locked safe—providing an extra layer of protection for your most sensitive data. However, this compartment is fragile and can be easily damaged by accidental overwrites or improper handling.{alertTip}

VeraCrypt supports the PBKDF2 Key Derivation Function (KDF) with various hash algorithms, including SHA-512, SHA-256, and RIPEMD-160. However, it does not yet support more advanced KDFs like Argon2id, which is available in LUKS2. Additionally, VeraCrypt is compatible with common filesystems such as Ext4, Btrfs, and NTFS.

Unlike LUKS, VeraCrypt supports cipher combinations such as AES-Serpent, AES-Twofish, Serpent-Twofish, and AES-Serpent-Twofish.

It’s worth noting that VeraCrypt is not as deeply integrated into Linux as LUKS, which may result in slightly lower performance.{alertInfo}


So, which encryption tool will you choose for your Linux system?

Creating an Encrypted Partition

To create an encrypted partition or disk on Linux, you can choose between two methods: command-line or graphical user interface (GUI). For LUKS, I recommend the command-line approach, as GUI tools often provide only basic configuration options. Conversely, VeraCrypt's native GUI offers a more user-friendly experience. The choice depends on your preference.

Before encrypting, you'll need to allocate space by creating a partition on any available free space on your disk. For a simpler process, I suggest using a GUI tool. If you're on a GTK-based desktop like GNOME, use Disks; for a Qt-based desktop, KDE Partition Manager is ideal. Alternatively, if you prefer the command line, follow the steps below to create a partition manually: 

  1. Identify Disks: Use `fdisk -l` to list available disks:

sudo fdisk -l{codeBox}
Identifying Disks with Fdisk
  1. Open fdisk:

sudo fdisk /dev/nvme0n1{codeBox}

Replace `/dev/nvme0n1` with your disk{alertWarning}

  1. Print Partition Table: View the current disk layout with the `p` command:
p{codeBox}

While `fdisk` often suggests suitable partition settings based on available space, it's crucial to verify these suggestions using the `p` command before proceeding.{alertTip}

  1. Create New Partition:

n{codeBox}

fdisk will often suggest default values for the first sector and last sector based on available free space.{alertTip}
Creating a New Partition Using Fdisk

  • Set Partition Type:

t(Enter partition number and type code){codeBox}

When fdisk prompts you to change the partition type, enter the partition number you want to modify and press Enter. You'll then be asked to provide the type code. Instead of using hex codes, you can enter aliases like Linux for a Linux filesystem partition, LVM for a Linux LVM partition, or Microsoft basic data for a Windows NTFS partition. If you're unsure, typing L will display a list of all available type codes.{alertTip}

  • Write Changes:

w{codeBox}
  1. Format the Partition: To format the newly created partition with a filesystem (e.g., Ext4), use the mkfs command:

sudo mkfs.ext4 /dev/nvme0n1p7{codeBox}

Replace /dev/nvme0n1p7 with the actual device name of your partition. {alertWarning}

Now, you can proceed to encrypt it using LUKS or VeraCrypt.

Encrypting a Partition or Disk with LUKS

As discussed in the previous section, when creating an encrypted partition using LUKS, there are several configuration options you can apply to tailor the encryption to your needs. Below are examples with various options explained. Since LUKS1 is less secure than LUKS2, I highly recommend using LUKS2.

Basic LUKS Initialization

The basic LUKS encryption of a partition can be done easily using a simple command line or a disk management tool such as Disks or KDE Partition Manager. If you use them to create the partition, you may notice the encryption option. 

The command-line method is as follows:
sudo cryptsetup luksFormat --type luks2 /dev/nvmeXnYpZ{codeBox}

This initializes a LUKS2-encrypted partition using default settings like AES with a 256-bit key and Argon2id for key derivation. Remember to replace the placeholder with the actual path to your NVMe partition (e.g., /dev/nvme0n1p7).{alertInfo}
Basic LUKS2 Partition Setup
If you prefer the GUI approach, you can select the encryption option during partition or disk file system creation in your favorite disk manager. It is worth noting that LUKS is not supported in Gparted, and the reason is unclear. When using a disk manager like Disks, you get an encrypted partition with your preferred file system type directly. However, when using the command-line approach, you need extra steps to store your sensitive data on it, which will be mentioned after highlighting the common advanced configuration options.{alertWarning}

Advanced LUKS Initialization

When creating an encrypted partition using LUKS2, there are several options and configurations you can apply to tailor the encryption to your needs. Below are examples with various options explained.

  • Specifying the Cipher and Key Size

sudo cryptsetup luksFormat --type luks2 --cipher aes-xts-plain64 --key-size 512 /dev/nvmeXnYpZ{codeBox}

Cipher: `aes-xts-plain64` is a common choice for disk encryption. Key Size: `512` bits (for AES-XTS, which splits into two 256-bit keys).{alertInfo}
  • Choosing a Different Hash Algorithm

sudo cryptsetup luksFormat --type luks2 --hash sha512 /dev/nvmeXnYpZ{codeBox}

Hash Algorithm: `sha512` is a stronger hash function used for passphrase strengthening compared to the default `sha256`.{alertInfo}
  • Using a Random Number Generator
sudo cryptsetup luksFormat --type luks2 --use-random /dev/nvmeXnYpZ{codeBox}

Randomness: `--use-random` increases security by using a more secure random number generator than the default `--use-urandom`.{alertInfo}

  • Using Argon2id Key Derivation

sudo cryptsetup luksFormat --type luks2 --pbkdf argon2id /dev/nvmeXnYpZ{codeBox}

KDF: `argon2id` is a modern and memory-hard KDF, better suited for protecting against brute-force attacks.{alertInfo}

  • Setting a Custom Iteration Time for Key Derivation

sudo cryptsetup luksFormat --type luks2 --iter-time 5000 /dev/nvmeXnYpZ{codeBox}

Iteration Time: `--iter-time` sets the time (in milliseconds) spent on passphrase processing to make brute-force attacks more difficult.{alertInfo}

  • Increasing the Number of Key Slots
sudo cryptsetup luksFormat --type luks2 --key-slot 8 /dev/nvmeXnYpZ{codeBox}

Key Slots: LUKS2 supports up to 8 key slots. Increasing this can allow more users or backup keys.{alertInfo}
  • Adding a Keyfile
Generate the Keyfile: dd if=/dev/urandom of=/path/to/keyfile bs=1024 count=4 && chmod 0400 /path/to/keyfile
This single line command generates a 4 KB keyfile with random data and then sets the file permissions to be readable and writable only by the root.{alertWarning}

sudo cryptsetup luksFormat --type luks2 --key-file /path/to/keyfile /dev/nvmeXnYpZ{codeBox}

Keyfile: This command sets up a new LUKS2-encrypted partition with a keyfile, enabling you to unlock the volume using both the keyfile and a passphrase for added security.{alertInfo}
  • Using a Detached LUKS2 Header
sudo cryptsetup luksFormat --type luks2 --header /path/to/header /dev/nvmeXnYpZ{codeBox}

Detached Header: This stores the LUKS header outside the encrypted partition, increasing security by keeping the header separate from the data.{alertInfo}
  • Creating an Encrypted Partition with Custom Sector Size
sudo cryptsetup luksFormat --type luks2 --sector-size 4096 /dev/nvmeXnYpZ{codeBox}

Sector Size: `--sector-size 4096` optimizes performance for modern drives, especially SSDs.{alertInfo}
  • Using a Cipher with GCM Mode (Authenticated Encryption)
sudo cryptsetup luksFormat --type luks2 --cipher aes-gcm /dev/nvmeXnYpZ{codeBox}

Cipher Mode: `aes-gcm` provides both encryption and authentication, though it's less common in disk encryption compared to XTS.{alertInfo}
  • Enabling Key Escrow
sudo cryptsetup luksFormat --type luks2 --master-key-file /path/to/keyfile /dev/nvmeXnYpZ{codeBox}

Key Escrow: This option allows the use of a pre-defined master key stored in a secure location, useful for enterprise environments where recovery keys are needed.{alertInfo}
  • Specifying the Use of TRIM on Encrypted Partition
sudo cryptsetup luksFormat --type luks2 --allow-discards /dev/nvmeXnYpZ{codeBox}

TRIM Support: `--allow-discards` enables TRIM support on SSDs, which helps maintain performance over time but may reduce security slightly by revealing which blocks are unused.{alertInfo}
  • Adding or Removing a Passphrase

sudo cryptsetup luksAddKey /dev/nvmeXnYpZ
sudo cryptsetup luksRemoveKey /dev/nvmeXnYpZ{codeBox}

  • A complete command might look like this:

sudo cryptsetup luksFormat --cipher aes-xts-plain64 --key-size 512 --hash sha512 --sector-size 4096 --pbkdf argon2id --iter-time 5000 --header /path/to/header --use-random /dev/nvmeXnYpZ{codeBox}

This command would:

  • Use AES with XTS mode and a 512-bit key.
  • Use SHA-512 for passphrase hashing.
  • Set the sector size to 4096 bytes.
  • Use Argon2id as the KDF.
  • Spend 5000 milliseconds in passphrase processing.
  • Store the LUKS header separately.
  • Use a secure random number generator for initializing the encryption.

These options allow you to fully customize the encryption process to suit your needs, balancing between security, performance, and usability. {alertSuccess}

Using the above command lines, you just created an encrypted partition block device without a filesystem within it. To store data, you need to create a filesystem:

  1. Open the LUKS Partition: Unlock the encrypted partition to make it available for formatting and use:
sudo cryptsetup open /dev/nvmeXnYpZ encrypted_partition (or give it a name you prefer){codeBox}

This creates a device at `/dev/mapper/encrypted_partition.{alertInfo}

  1. Create a Filesystem on the Encrypted Partition: Format the opened LUKS device with the desired filesystem (e.g., ext4):
sudo mkfs.ext4 /dev/mapper/encrypted_partition{codeBox}

Once the encrypted partition is created, you can easily access it using your preferred file manager. Simply mount the decrypted partition, and it will appear as a regular storage device.{alertInfo}
  1. Mount the Encrypted Partition: Mount the encrypted partition to a directory:
sudo mount /dev/mapper/encrypted_partition /mnt{codeBox}

  1. Close the Encrypted Partition: When done, unmount and close the encrypted partition:
sudo umount /mnt
sudo cryptsetup close encrypted_partition{codeBox}

Always unmount the partition before closing the LUKS container to avoid data corruption.{alertWarning}
  1. Additional LUKS Options and Management
  • Check LUKS Status:

sudo cryptsetup luksDump /dev/nvmeXnYpZ{codeBox}

  • Change the encrypted partition label:

sudo cryptsetup config /dev/nvmeXnYpZ --label="NewLabel" {codeBox}

Replace /dev/nvmeXnYpZ with your device path and "NewLabel" with the desired label.{alertInfo}
  • Backup LUKS Header: It is highly recommended to backup the LUKS header. If the header is damaged, you will lose access to your data:
sudo cryptsetup luksHeaderBackup /dev/nvmeXnYpZ --header-backup-file /path/to/backup/backup_header.img{codeBox}

After our deep dive into LUKS and its intricacies, let's explore how to create encrypted partitions using VeraCrypt.

Encrypting a Partition or Disk with VeraCrypt

While VeraCrypt might have been available in some Linux repositories in the past, it's no longer commonly included. Here's how to install and use it:

  1. Download VeraCrypt: Visit the official website (https://www.veracrypt.fr/en/Downloads.html) and download the appropriate installer for your Linux distribution. Make sure to choose the GUI (Graphical User Interface) version for a user-friendly experience.
  2. Use your package manager: Most Linux distributions have software centers or package managers (like Ubuntu Software, GNOME Software, or KDE Discover). Locate the downloaded VeraCrypt, open it with the package manager, and click the "Install" button. 

Once VeraCrypt is installed, you can easily launch it from your applications menu and start creating encrypted volumes:

  1. Open VeraCrypt: Launch the VeraCrypt application.
  2. Create Volume: Click on the “Create Volume” option to start the encryption process.
  1. Select Encryption Type: Choose “Encrypt non-system partition/drive” and click “Next.”
  1. Volume Type: Decide whether to create a standard VeraCrypt volume or a hidden VeraCrypt volume. Click “Next.”
  1. Select Device: Click on “Select Device” to choose the partition or disk you want to encrypt. Ensure you select the correct partition or disk as this process will overwrite existing data.
  1. Configure Encryption: Configure the encryption algorithm and key length. Click “Next.”
  1. Password and Keyfiles: Create a strong password for the volume and optionally use keyfiles for added security. To use the keyfile, click “Use Keyfile” and browse to the location where you saved it.
To create a keyfile using VeraCrypt, go to the “Tools” menu and select “Keyfile Generator.” Configure the hash algorithm, randomness (by moving your mouse), keyfile size, and the number of keyfiles you want. Enter a base name for the keyfile and click the “Generate and Save Keyfiles” button. Save the generated keyfile to a secure location, such as an encrypted USB drive like the Nitrokey Storage 2, to ensure its safety (indeed, your safety).{alertInfo}
  1. Large Files Option: Specify whether you intend to store “Large files” on the encrypted volume (yes or no).
  1. Choose Filesystem: Select the filesystem you want to use for the volume from the available options.
  1. Cross-Platform Compatibility: Decide whether you want the volume to be accessible from other operating systems (click “Next”).
  1. Configure Randomness: Adjust the randomness settings for the header and master key by moving your mouse to generate sufficient entropy.
  1. Format Volume: Click “Format” to begin the formatting process and wait until it completes.

Once the partition is encrypted, you can mount it using a file manager to start storing and accessing your secured data.

I should add a note that you may need to mount your newly encrypted partition through the VeraCrypt interface. Click 'Select Device', choose the correct partition, and then click 'Mount'. The partition should then appear in your file manager. {alertWarning}

After you're done using the encrypted partition, right-click on the mounted partition/drive in your file manager and select "Unmount" to protect your data and avoid corruption, especially with external drives. Then, open VeraCrypt, select the mounted volume, and click "Dismount" to securely disconnect the encrypted partition. 

Conclusion

To sum up, disk encryption is a crucial step for safeguarding your sensitive data on Linux. Whether you opt for LUKS with its deep integration into the Linux ecosystem or VeraCrypt for its ease of use and flexibility, both provide robust protection against unauthorized access. The choice ultimately depends on your specific needs, preferences, and comfort level with command-line tools versus graphical interfaces.

While we've covered the essential steps to set up encrypted partitions and disks using these tools, there's always room to enhance security further. One approach is to consider integrating hardware-based security mechanisms, such as a FIDO security key or a Trusted Platform Module (TPM), as an additional layer of protection for your encrypted drives.

Would you be interested in a future blog post that dives into how to implement hardware-based security measures like FIDO security keys and TPMs to bolster the security of your encrypted partitions? Let me know in the comments or reach out to me directly!

At Linux-Tech&More, I’m dedicated to offering an ad-free, uninterrupted reading experience, free from AdSense and automated ads. If you enjoy my blog and want to support it, consider contributing via
Your support makes a difference!{alertIdea}
Djalel Oukid

Science teacher, PhD student, Master degree in Microbial biotechnology , Microbiologist, designer, video editor, podcaster & blogger. linkedin portfolio github

Comments are welcomed and encouraged on this blog. Spam, abusive and off-topics comments will be deleted. Please read our Comments policy before commenting.

Post a Comment (0)
Previous Post Next Post
Blackview BV9900 Pro Thermal Camera Mobile Phone Helio P90 Octa Core 8GB+128GB IP68 Rugged Smartphone 48MP Quad Rear Camera