Jay Taylor's notes

back to listing index

HowTo: Linux Hard Disk Encryption With LUKS [ cryptsetup Command ]

[web search]
Original source (www.cyberciti.biz)
Tags: encryption linux fde luks www.cyberciti.biz
Clipped on: 2017-05-31

Skip to content
Image (Asset 1/6) alt= Worried about my data.

Dear Worried Linux user,

That’s actually a great question. Many enterprises, small business, and government users need to encrypt their laptop to protect confidential information such as customer details, files, contact information and much more. Linux supports the following cryptographic techniques to protect a hard disk, directory, and partition. All data that is written on any one of the following techniques will automatically encrypted, and decrypted on the fly.

Linux encryption methods

There are two methods to encrypt your data:

#1: Filesystem stacked level encryption

  1. eCryptfs – It is a cryptographic stacked Linux filesystem. eCryptfs stores cryptographic metadata in the header of each file written, so that encrypted files can be copied between hosts; the file will be decrypted with the proper key in the Linux kernel keyring. This solution is widely used, as the basis for Ubuntu’s Encrypted Home Directory, natively within Google’s ChromeOS, and transparently embedded in several network attached storage (NAS) devices.
  2. EncFS -It provides an encrypted filesystem in user-space. It runs without any special permissions and uses the FUSE library and Linux kernel module to provide the filesystem interface. You can find links to source and binary releases below. EncFS is open source software, licensed under the GPL.

#2: Block device level encryption

  1. Loop-AES – Fast and transparent file system and swap encryption package for linux. No source code changes to linux kernel. Works with 3.x, 2.6, 2.4, 2.2 and 2.0 kernels.
  2. VeraCrypt – It is free open-source disk encryption software for Windows 7/Vista/XP, Mac OS X and Linux based on TrueCrypt codebase.
  3. dm-crypt+LUKS – dm-crypt is a transparent disk encryption subsystem in Linux kernel v2.6+ and later and DragonFly BSD. It can encrypt whole disks, removable media, partitions, software RAID volumes, logical volumes, and files.

In this post, I will explain how to encrypt your partitions using Linux Unified Key Setup-on-disk-format (LUKS) on your Linux based computer or laptop.

Step #1: Install cryptsetup utility

You need to install the following package. It contains cryptsetup, a utility for setting up encrypted filesystems using Device Mapper and the dm-crypt target. Debian / Ubuntu Linux user type the following apt-get command:
# apt-get install cryptsetup
Sample outputs:

Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following extra packages will be installed:
  cryptsetup-bin libcryptsetup4
Suggested packages:
The following NEW packages will be installed:
  cryptsetup cryptsetup-bin libcryptsetup4
0 upgraded, 3 newly installed, 0 to remove and 7 not upgraded.
Need to get 168 kB of archives.
After this operation, 669 kB of additional disk space will be used.
Do you want to continue [Y/n]? y
Get:1 http://ap-northeast-1.ec2.archive.ubuntu.com/ubuntu/ precise/main libcryptsetup4 amd64 2:1.4.1-2ubuntu4 [55.8 kB]
Get:2 http://ap-northeast-1.ec2.archive.ubuntu.com/ubuntu/ precise/main cryptsetup-bin amd64 2:1.4.1-2ubuntu4 [32.2 kB]
Get:3 http://ap-northeast-1.ec2.archive.ubuntu.com/ubuntu/ precise/main cryptsetup amd64 2:1.4.1-2ubuntu4 [80.0 kB]
Fetched 168 kB in 0s (268 kB/s)  
Preconfiguring packages ...
Selecting previously unselected package libcryptsetup4.
(Reading database ... 25374 files and directories currently installed.)
Unpacking libcryptsetup4 (from .../libcryptsetup4_2%3a1.4.1-2ubuntu4_amd64.deb) ...
Selecting previously unselected package cryptsetup-bin.
Unpacking cryptsetup-bin (from .../cryptsetup-bin_2%3a1.4.1-2ubuntu4_amd64.deb) ...
Selecting previously unselected package cryptsetup.
Unpacking cryptsetup (from .../cryptsetup_2%3a1.4.1-2ubuntu4_amd64.deb) ...
Processing triggers for man-db ...
Processing triggers for ureadahead ...
Setting up libcryptsetup4 (2:1.4.1-2ubuntu4) ...
Setting up cryptsetup-bin (2:1.4.1-2ubuntu4) ...
Setting up cryptsetup (2:1.4.1-2ubuntu4) ...
update-initramfs: deferring update (trigger activated)
Processing triggers for libc-bin ...
ldconfig deferred processing now taking place
Processing triggers for initramfs-tools ...
update-initramfs: Generating /boot/initrd.img-3.2.0-31-virtual

RHEL / CentOS / Fedora Linux user type the following yum command:
# yum install cryptsetup-luks

Step #2: Configure LUKS partition

Image (Asset 2/6) alt= # cryptsetup -y -v luksFormat /dev/xvdc
Sample outputs:

This will overwrite data on /dev/xvdc irrevocably.
Are you sure? (Type uppercase yes): YES
Enter LUKS passphrase: 
Verify passphrase: 
Command successful.

This command initializes the volume, and sets an initial key or passphrase. Please note that the passphrase is not recoverable so do not forget it.Type the following command create a mapping:
# cryptsetup luksOpen /dev/xvdc backup2
Sample outputs:

Enter passphrase for /dev/xvdc:

You can see a mapping name /dev/mapper/backup2 after successful verification of the supplied key material which was created with luksFormat command extension:
# ls -l /dev/mapper/backup2
Sample outputs:

lrwxrwxrwx 1 root root 7 Oct 19 19:37 /dev/mapper/backup2 -> ../dm-0

You can use the following command to see the status for the mapping:
# cryptsetup -v status backup2
Sample outputs:

/dev/mapper/backup2 is active.
  type:    LUKS1
  cipher:  aes-cbc-essiv:sha256
  keysize: 256 bits
  device:  /dev/xvdc
  offset:  4096 sectors
  size:    419426304 sectors
  mode:    read/write
Command successful.

You can dump LUKS headers using the following command:
# cryptsetup luksDump /dev/xvdc

Step #3: Format LUKS partition

First, you need to write zeros to /dev/mapper/backup2 encrypted device. This will allocate block data with zeros. This ensures that outside world will see this as random data i.e. it protect against disclosure of usage patterns:
# dd if=/dev/zero of=/dev/mapper/backup2
The dd command may take many hours to complete. I suggest that you use pv command to monitor the progress:
# pv -tpreb /dev/zero | dd of=/dev/mapper/backup2 bs=128M
Sample outputs:

dd: error writing '/dev/mapper/backup2': No space left on device                                                                                                            ]
 200GiB 0:16:47 [ 203MiB/s] [                      <=>                                                                                                                      ]
1600+1 records in
1599+1 records out
214746267648 bytes (215 GB, 200 GiB) copied, 1008.19 s, 213 MB/s

To create a filesystem i.e. format filesystem, enter:
# mkfs.ext4 /dev/mapper/backup2
Sample outputs:

mke2fs 1.42.13 (17-May-2015)
Creating filesystem with 52428288 4k blocks and 13107200 inodes
Filesystem UUID: 1c71b0f4-f95d-46d6-93e0-cbd19cb95edb
Superblock backups stored on blocks: 
	32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208, 
	4096000, 7962624, 11239424, 20480000, 23887872

Allocating group tables: done                            
Writing inode tables: done                            
Creating journal (32768 blocks): done
Writing superblocks and filesystem accounting information: done     

To mount the new filesystem at /backup2, enter:
# mkdir /backup2
# mount /dev/mapper/backup2 /backup2
# df -H
# cd /backup2
# ls -l

How do I unmount and secure data?

Type the following commands:
# umount /backup2
# cryptsetup luksClose backup2

How do I mount or remount encrypted partition?

Type the following command:
# cryptsetup luksOpen /dev/xvdc backup2
# mount /dev/mapper/backup2 /backup2
# df -H
# mount

Sample outputs:

Image (Asset 3/6) alt= See shell script wrapper that opens LUKS partition and sets up a mapping for nas devices.

Can I run fsck on LUKS based partition / LVM volume?

Yes, you can use the fsck command On LUKS based systems:
# umount /backup2
# fsck -vy /dev/mapper/backup2
# mount /dev/mapper/backup2 /backu2

See how to run fsck On LUKS (dm-crypt) based LVM physical volume for more details.

How do I change LUKS passphrase (password) for encrypted partition?

Type the following command
### see key slots, max -8 i.e. max 8 passwords can be setup for each device ####
# cryptsetup luksDump /dev/xvdc
# cryptsetup luksAddKey /dev/xvdc

Enter any passphrase: 
Enter new passphrase for key slot: 
Verify passphrase: 

Remove or delete the old password:
# cryptsetup luksRemoveKey /dev/xvdc
Please note that you need to enter the old password / passphrase.

Check out related media

This tutorial also available in video format:

(Video 01: cryptsetup command demo)


You now have an encrypted partition for all of your data.


  1. LUKS encrypts entire block devices and is therefore well-suited for protecting the contents of mobile devices such as removable storage media (usb pen) or laptop disk drives.
  2. You can also use with your nas server to protect backups.
  3. Intel and AMD cpus with AES-NI (Advanced Encryption Standard Instruction Set) can accelerate dm-crypt based encryption for Linux kernel v2.6.32+. This will speed up harddisk encryption.
  4. Works with swap partition too so that your laptop can use hibernation feature (suspend-to-disk) that writes out the contents of RAM to the swap partition before turning off the machine.


  1. LUKS only support upto 8 passwords i.e. only 8 users can have distinct access keys to the same device.
  2. LUKS is also not recommend for applications requiring file-level encryption.

For more information see cryptsetup man page and read RHEL 6.x documentation.


Your support makes a big difference:

I have a small favor to ask. More people are reading the nixCraft. Many of you block advertising which is your right, and advertising revenues are not sufficient to cover my operating costs. So you can see why I need to ask for your help. The nixCraft, takes a lot of my time and hard work to produce. If you use nixCraft, who likes it, helps me with donations:

Become a Supporter Make a contribution via Paypal/Bitcoin

T-shirt: Sysadmin because even developers need heros

Image (Asset 4/6) alt= This command not working in my rhel5.4

  • Should I make a partition first? Like /dev/sdb1 and run the dd command on sdb1, and make sdb1 the luks container? Or should I run dd on /dev/sdb first, then create sdb1 and make that my luks container? (sdb1 will be the full partition size)

  • Is There any way to setup luks encryption after installing Fedora 22 ??

    1. Install the package that contains cryptsetup if its not already on there.

  • Looking for someone to attempt data recovery of a LUKs partition?
    Anyone interested. Can pay with BTC if you get it back.

  • Thanks dude. Added to Favorites.

  • Skip the delay contributed by dd an just ‘pv -tpreb /dev/urandom > /dev/to_be_wiped’ and do it BEFORE cryptsetup , not to the already crypt-formatted
    /dev/mapper/backup2. ( However the author’s method works too).

    And save the header with ‘cryptsetup luksHeaderBackup –header-backup-file ‘ , accidents do happen and if the header is lost kiss the encrypted data goodbye . ( Make sure the saved header does not get in hands of an adversary who’ll then be able to decrypt your data with it…though not very easily). Just look how many people on the web asking how to restore a corrupted one way or another LUKS volume only to find the hard way it’s not possible. With the LUKS header saved the volume is recoverable. While at it save the partition layout as well with ‘sfdisk -d /dev/your_disk > disk_part.backup’ , if it’s partitioned prior to crypt-formatting it, or if you partition inside the volume ‘sfdisk -d /dev/mapper/backup2 > backup2-part.backup’

    1. On any Intel CPU with AES-NI (anything manufactured after 2008), the dd command is likely to be faster. Encryption uses AES, which is considerably accelerated by AES-NI in hardware. Even very old CPUs achieve about 3 cycles per byte with AES-NI; at this rate, the encryption is likely faster than the disk bandwidth. /dev/urandom by contrast uses hashing operations, which are performed in software. The upcoming Skylake CPUs are supposed to include hardware-accelerated SHA extensions, which may make hashing competitive with encryption, but we’ll have to wait for the hardware to come out before we can compare performance.

  • Thanks for this great article, very helpful and straight to the point. Luks is faster than Truecrypt on my Banana Pi ARM computer!

  • Why write zeroes to the encrypted partition? Why not fill the drive with zeroes before it is encrypted? This should be much faster

    1. because then any attacker would know where you were storing your data, and given a linux file system has a standard layout would have a head start correlating cipher text with the likely plain text.

  • Wondering: if you fill with /dev/zero, then until the disk is full there will be large regions that will just hold an encrypted /dev/zero (assuming disk space is not allocated at random). Could someone take advantge of this (clear data: all zeroes, plus encrypted data: what is found on the disk) to recompute the key?

    Missing: how to add automatic open/mount to boot/config sequence to automatically mount a second fixed disk at boot.

    This said, nice and clear instructions.

  • MeAndJuliaDownByTheSchoolYard says:

    The new cryptsetup syntax for open and close of luks devices is ‘cryptsetup open –type luks /dev/sdg1 backup’ and ‘cryptsetup close –type luks backup’. Strnagely similar syntax for ‘format’, ‘dump’, etc doesn’t seem to be implemented yet.

  • Hi, I need full disk encryption in my db server where the db is in /usr/local/bin and its suse Linux 11. Please let me know how to perform this on my system.

  • 1. But this way you can only edit the usb if you are root? Is it possible to change this with
    # chmod 777 backup2
    To make the usb not read-only?

    2. usb:s often often have name like /sdf or /sdf1. which one should I use when I type the commands – sdf or sdf1?

  • I’ve read you can use shred on a device also

    shred -v –iterations=1 /dev/[devicename]

  • Only use the filesystem with root? if you going step by step the default use is for root.

  • I think there are mistake. You should initially fill device my random bytes not zeros i.e.

    pv -tpreb /dev/urandom | dd of=/dev/mapper/backup2 bs=128M
    dd if=/dev/urandom of=/dev/mapper/backup2

    1. MeAndJuliaDownByTheSchoolYard says:

      Indeed, it is bad advice to use /dev/zero to fill the device. I use ‘dd if=/dev/urandom of=foo bs=1M’ which is a little quicker than using the default 4k block size.

      1. /dev/zero is sufficient and much faster. It’s not necessary to use /dev/urandom because the disk is already encrypted and the randomness is provided by the cypher, you just have to make sure that the device is filled. It should not be possible to distinguish encrypted zero-fill data and encrypted random data :)

        1. no, because filling the plain text layer with all zeroes gives anyone trying to break the security a head start.
          it’s basic cryptography101, don’t ever let the attacker know what the plain text is for a given cipher output.

          1. Charles Staal says:

            It’s not ONLY zeros. Once one bit of data is in there your argument is null. Even so, its still null with modern ciphers. Maybe if you knew more than just ‘101’…

            1. ok, you still have sector headers and so on, and these are predictable. An attacker trying to crack your encrypted disk will be looking specifically for patterns which may be caused because the disk was filled with zeroes.
              Since basic cryptography says you should never give an attacker the plain text and the cipher text, you’re leaking information.

              1. Modern encryption schemes are specifically designed to withstand attack from adversaries who know both plaintext and ciphertext. They have to be, since there is too much known plaintext on the internet. (For example, an adversary can observe the IP addresses that your web browser is connecting to, and connect to those web sites himself, thereby learning a plaintext/ciphertext pair.)

                There is no concern whatsoever from leaking known plaintext. None. I’m a professional cryptographer. Anyone who says otherwise is at best misguided and at worst vulnerable to disaster because they’re worrying about the wrong thing.

    2. DucKienTruong says:

      /dev/zero is sufficient and much faster. It’s not necessary to use /dev/urandom because the disk is already encrypted and the randomness is provided by the cypher, you just have to make sure that the device is filled. It should not be possible to distinguish encrypted zero-fill data and encrypted random data :)

  • Regarding monitoring of the dd process, an easier to remember and more portable method is as such:

    # kill -USR1 $pid_of_dd

    This will cause the to output the number of bytes copied, current run time and throughput to the terminal running the ‘dd’ command.

  • There is a project that gives a GUI tool to manage cryptsetup LUKS and PLAIN volumes as well as truecrypt volumes.The project is hosted at: http://code.google.com/p/zulucrypt/

  • # I strive on raring ringtail (gnome) backed by crypt-luks (entire 500GB) + encfs (over dropbox/google drive). m/

  • My entire disk is encrypted using LUKS ..Mistakenly i deleted one imporatnt *.nsf file. Using some software i could restore that deleted file but it says PGP/MIME encrypted header ..Do we have any way to decrypt the single file ..

  • For pv -tpreb /dev/zero | dd of=/dev/mapper/backup2 bs=128M I have a 1TB drive. The bs=128 is that OK?

  • Hi,

    I have a RHEL 6.3 laptop with 500GB hard disk. The entire disk is encrypted via LUKS.

    I want to create a 250 GB partition on my disk to be able to install Windows7 on it. I wish to have RHEL/Windows dual boot on my laptop.

    But, I think without de-crypting the entire HDD, its not possible to create a new partition. Can you please help me on this? I would be greatly helpful to you.


    1. Oops… typo in last sentence…. I would be greatly thankful to you !!!

      1. Read this thread. If I were you I will backup all data before resizing anything. Good luck!

  • “RHEL / CentOS / Fedora Linux user type the following yum command:
    # apt-get install cryptsetup-luks”
    # yum install cryptsetup-luks


    1. Thanks for the heads up!

  • usbs can be carried within a baggy or balloon within a user’s rectum once slid into the anus.

    1. And just how often do you use this technique?

    2. . Look up ‘microSD coin container’ so you don’t have to violate yourself.

  • Hello NixCraft, good tutorial using cryptsetup,

    just advice cryptsetup now had new release by 3 days ago,, :D


    *compile from source will help us to know more ;)


  • How do you do this on FreeBSD?

  • Truecrypt – It is free open-source disk encryption software for Windows 7/Vista/XP, Mac OS X and Linux.

    You may want to check your statement about Truecrypt.

    If it’s not available in Debian, it cannot be opensource.

    1. No, TrueCrypt is Open Source (at least that’s what their website says), though it has its own license (non-GPL), which might be why most distros don’t have it.
      You can download the source here:

      Besides, not even Debian could have absolutely every piece of Free and Open Source Software out there.

      And if you need it, here is a program based off of TrueCrypt:

      Another thing: Fedora stopped providing TrueCrypt as well. Here is their opinion on it.

    2. cryptsetup can handle truecrypt containers and tcplay is a cli tool for it , and even a GUI version ZuluCrypt.

  • Leave a Comment

    Recaptcha requires verification
    I'm not a robot

    Image (Asset 5/6) alt=