Encryption

Contents

  1. GnuPG
  2. Cryptsetup
    1. Encrypt Disk Image File with a Passphrase
    2. Encrypt Physical Device with a Key File

1. GnuPG

Encrypt a secret file using a passphrase.

gpg -o encrypted.txt.gpg -c secret.txt
# Type passphrase.

Decrypt with a a passphrase.

gpg -o decrypted.txt -d encrypted.txt.gpg
# Type passphrase.

2. Cryptsetup

2.1. Encrypt Disk Image File with a Passphrase

Create and encrypt the disk image. In this case it is 50 megabytes and only uses a 256 bit AES cipher. It is probably better to use a mix of ciphers.

head -q -c 50MB /dev/urandom > secret.img
/sbin/cryptsetup -q --cipher aes --key-size 256 luksFormat secret.img
# Type passphrase.

Then as root (using sudo), format the file system.

sudo cryptsetup luksOpen secret.img secretimg
# Type passphrase.
sudo mkfs.ext4 /dev/mapper/secretimg
sudo cryptsetup luksClose secretimg

Now mounting to /mnt/point/ will involve:

sudo cryptsetup luksOpen secret.img secretimg
# Type passphrase.
sudo mount /dev/mapper/secretimg /mnt/point

And unmounting involves:

sudo umount /mnt/point
sudo cryptsetup luksClose secretimg

2.2. Encrypt Physical Device with a Key File

A key file is essentially a longer password that is stored in a file. For something like an encrypted backup drive, using a key file makes backing up more seamless since no password is required. It may be reasonable to assume that an attacker will not have access to your own computer, so a key file can even improve security!

The steps are mostly the same, but we must generate a random key and specify it with the --key-file when invoking cryptsetup. In this case, we use the variable $secretdev to hold /dev/sdc1, but it could just as well be secret.img as before.

secretdev=/dev/sdc1
keyfile=secret.keyfile
mappedname=secretdev
head -q -c 2048 /dev/random > $keyfile
sudo cryptsetup -q --cipher aes --key-size 256 --key-file $keyfile luksFormat $secretdev
sudo cryptsetup --key-file $keyfile luksOpen $secretdev $mappedname
sudo mkfs.ext4 /dev/mapper/$mappedname
sudo cryptsetup luksClose $mappedname

That's all there is to it!