Ubuntu Flash Drive Encryption Script

I was researching methods to encrypt USB flash drives, to protect personal data in the event they’re lost or stolen, and I found a few good write-ups on the subject using tools available in Ubuntu. Although the current distribution of Gnome includes pretty good support for auto-detecting and prompting for the password for encrypted drives, I couldn’t find any completely baked tools for encrypting the drives. So I wrote a simple script to streamline the process.

#!/bin/bash
set -e
 
echo "Drive Encrypter"
 
# Determine the device name.
mount # Display all mounted devices to help the user find the device name.
read -p "What is device name (e.g. /dev/<devicename>, from the mount list above)? " -e DEVICE
 
# Verify all required packages are installed.
echo "Checking packages..."
sudo apt-get install cryptsetup
sudo modprobe dm-crypt
 
# Overwrite with random data in order to slow down an attack on the encryption.
echo "Erasing device..."
umount /dev/$DEVICE
sudo badblocks -c 10240 -s -w -t random -v /dev/$DEVICE
 
echo "Creating encrypted partition..."
sudo cryptsetup --verbose --verify-passphrase luksFormat /dev/$DEVICE
sudo cryptsetup luksOpen /dev/$DEVICE $DEVICE
sudo mkfs.ext3 /dev/mapper/$DEVICE
sudo cryptsetup luksClose $DEVICE
 
echo "Done."
echo "Remove the drive and then plug it back in, and you should be prompted for a password to access the device."
#Note, you may have to run this to access the device from a normal account:
#sudo chown -R user:user /media/mountpoint

Leave a Reply