Linux Encryption – How to Set Up Encrypted Swap File in Linux

arch linuxencryptionlinuxswap

2017 WARNING! The accepted answer appears to work, but with recent kernels I discovered that the system would hang as soon as it started swapping. If you attempt using an encrypted swap file, make sure that it actually swaps properly. It took me a long time to figure out why my system kept locking up for no apparent reason. I've gone back to using an encrypted swap partition, which does work correctly.


How do I set up an encrypted swap file (not partition) in Linux? Is it even possible? All the guides I've found talk about encrypted swap partitions, but I don't have a swap partition, and I'd rather not have to repartition my disk.

I don't need suspend-to-disk support, so I'd like to use a random key on each boot.

I'm already using a TrueCrypt file-hosted volume for my data, but I don't want to put my swap in that volume. I'm not set on using TrueCrypt for the swap file if there's a better solution.

I'm using Arch Linux with the default kernel, if that matters.

Best Answer

Indeed, the page describes setting up a partition, but it's similar for a swapfile:

dd if=/dev/urandom of=swapfile.crypt bs=1M count=64
loop=$(losetup -f)
losetup ${loop} swapfile.crypt
cryptsetup open --type plain --key-file /dev/urandom ${loop} swapfile
mkswap /dev/mapper/swapfile
swapon /dev/mapper/swapfile

The result:

# swapon -s
Filename                                Type            Size    Used    Priority
/dev/mapper/swap0                       partition       4000176 0       -1
/dev/mapper/swap1                       partition       2000084 0       -2
/dev/mapper/swapfile                    partition       65528   0       -3

swap0 and swap1 are real partitions.

Related Question