apt-get install cryptsetup
Using dm-crypt/LUKS/cryptsetup by doing the following steps:
1. Create a sparse disk image file: dd if=/dev/zero of=IMAGEFILE bs=1 count=1 seek=SIZE
2. Generate a random key in a file: dd if=/dev/random of=KEYFILE bs=1024 count=1
3. Use cryptsetup luksFormat –key-file KEYFILE –cipher aes-xts-plain –size 512 IMAGEFILE (Or use another cipher and key length. Note that 512 here will give you AES with 256 bits because of XTS.) Example 2: cryptsetup luksFormat –key-file KEYFILE –cipher
aes-xts-plain64:sha512 -s 512 IMAGEFILE
4. Open crypt container: cryptsetup luksOpen –key-file KEYFILE IMAGEFILE NAME
5. Create file system on /dev/mapper/NAME.
6. Mount file system as usual.
Your script would just have to do steps 4 and 6. For unmounting/closing, umount the file system and call cryptsetup luksClose NAME.
Note that using sparse files will leak the information which sectors of the disk have been used already (the same way as not overwriting a partition with random data before encrypting it). It is up to you to decide whether this is ok for you.
Also note that deleting files will not make the disk image smaller. The sparse file will grow monotonically.
By: P Wendler