Just hiding a file or directory is not enough for your security because anyone with a slight bit of technical language can easily view them whether using a command line or using the file manager. That is why you need to encrypt anything that is essential to you, and that you don’t want others to look at.
On Linux, there are several ways using which, you can encrypt a file or directory or the whole FileSystem using GnuPG or the LUKS disk encryption respectively.
In this tutorial, I will show you how to encrypt a file or directory with the GnuPG tool as well as the zip utility.
Encrypting files using the GPG utility
Using the ‘gpg’ utility, we can encrypt or decrypt a file using two methods, namely a password or a key file. We are going to set up a password to protect a file. We can use the -c option along with the ‘gpg’ command in order to encrypt a file. For example:
gpg -c <filename>
A box will appear on the Terminal interface, and it will ask you to enter a secure password, type your password and then press Enter. Make sure that you do not forget the passphrase, else, you will not be able to access your file after encryption.
A new wile with the extension gpg will be created and when you try to read the content of the file, you will not be able to do so.
Encrypting a directory using gpg tool
This method is not recommended if you are encrypting a directory, you can move to the zip & encryption procedure instead if you have any important directory to encrypt.
It will be easier if you just compress the directory and then encrypt the archive using gpg command. To compress a directory, you should use the tar command like this:
tar -cf archive.tar <directory name>
Once the directory is archived, you can encrypt it using the gpg command :
gpg -c archive.tar
Again, enter your password when prompted, you have now successfully encrypted both files and the directory successfully.
Decrypt a file using gpg command.
To decrypt the encrypted files/directories, you can use the gpg command like this :
gpg -d <directory/file>.gpg
You will be asked for a password to decrypt the file, type it in and then press enter.
Encrypt a directory using zip
To encrypt a directory using the zip command, you should use the –encrypt option along with the command. You can use the command to encrypt several files like this:
zip --encrypt encrypted.zip <file>...<file10>
To encrypt a directory, you can use this command:
zip -r --encrypt encypted2.zip <directory>
To decrypt a file, simply use the ‘unzip‘ command like this:
unzip encrypted.zip
Summary
Well, that’s about it. However, you can also create a private key for yourself using the gpg key using the gpg command like this :
gpg --full-gen-key
I hope, using this tutorial, you have successfully learned how to encrypt or decrypt a file on Linux using the Terminal. Let me know in the comments down below if you have any confusion/questions regarding this topic in the comments.