Linux File Encryption and Decryption: Complete Guide

File encryption is essential for protecting sensitive data, especially when transmitting files over email, storing them in cloud services, or sharing them across networks. Linux provides powerful command-line tools for encrypting and decrypting files, with GPG (GNU Privacy Guard) being the most widely used and trusted solution. This comprehensive guide covers multiple encryption methods in Linux, from basic GPG encryption to advanced techniques for securing your data.

Introduction to File Encryption in Linux

File encryption converts readable data into an encoded format that can only be accessed with the correct password or key. This protects sensitive information from unauthorized access, even if files are intercepted during transmission or stolen from storage devices. Linux offers several encryption tools, each suited for different use cases: GPG for general-purpose file encryption, OpenSSL for cryptographic operations, and specialized tools for full-disk encryption.

Encrypting Files with GPG

What is GPG?

GNU Privacy Guard (GPG) is a free implementation of the OpenPGP standard that provides cryptographic privacy and authentication. It’s included by default in most Linux distributions and offers strong encryption using various algorithms including AES, RSA, and more.

Basic File Encryption with GPG

Encrypt a file with symmetric encryption (password-based):

# Encrypt test.txt
gpg -c test.txt

When you run this command, a popup window or terminal prompt will appear asking you to enter a password twice for confirmation. After successful encryption, a new file test.txt.gpg is created in the same directory. This encrypted file cannot be read without the correct password.

Verify Encryption

To confirm the file is encrypted and unreadable:

# Try to view encrypted file content
cat test.txt.gpg
# Output will show encrypted binary data, not readable text

Decrypting Files with GPG

Basic Decryption

# Decrypt test.txt.gpg
gpg test.txt.gpg

You will be prompted to enter the password you set during encryption. After successful authentication, GPG creates the decrypted file test.txt in the current directory, restoring the original readable content.

Decrypt to Different Filename

# Decrypt and specify output filename
gpg -o decrypted-file.txt test.txt.gpg

# Decrypt to different directory
gpg -o /home/user/documents/myfile.txt test.txt.gpg

Advanced GPG Encryption Options

Specify Encryption Algorithm

# Use AES256 encryption explicitly
gpg -c --cipher-algo AES256 sensitive.txt

# Use AES128
gpg -c --cipher-algo AES128 document.pdf

Encrypt with Compression

# Encrypt and compress (smaller file size)
gpg -c --compress-algo zip document.txt

# No compression
gpg -c --compress-algo none largefile.bin

Non-Interactive Encryption (Scripting)

# Encrypt without password prompt (use with caution)
echo "mypassword" | gpg --batch --yes --passphrase-fd 0 -c file.txt

# Using passphrase file
gpg --batch --yes --passphrase-file password.txt -c document.pdf

Encrypting Files with OpenSSL

OpenSSL provides another method for file encryption with different algorithms and options:

Encrypt with OpenSSL

# Encrypt using AES-256-CBC
openssl enc -aes-256-cbc -salt -in file.txt -out file.txt.enc

# Encrypt with password from command line
openssl enc -aes-256-cbc -salt -in file.txt -out file.txt.enc -k mypassword

Decrypt with OpenSSL

# Decrypt file
openssl enc -d -aes-256-cbc -in file.txt.enc -out file.txt

# Decrypt with base64 encoding
openssl enc -d -aes-256-cbc -a -in file.txt.enc -out file.txt

List Available Ciphers

# Show all encryption algorithms available
openssl enc -ciphers

Encrypting Multiple Files

Archive and Encrypt

# Create tar archive and encrypt
tar czf - directory/ | gpg -c > directory.tar.gz.gpg

# Decrypt and extract
gpg -d directory.tar.gz.gpg | tar xzf -

Batch Encrypt Multiple Files

# Encrypt all .txt files in directory
for file in *.txt; do gpg -c "$file"; done

# Encrypt with same password for all files
for file in *.pdf; do
  echo "password123" | gpg --batch --yes --passphrase-fd 0 -c "$file"
done

File Encryption Best Practices

Password Security

  • Use strong passwords: Minimum 12 characters with uppercase, lowercase, numbers, and symbols
  • Never embed passwords: Avoid hardcoding passwords in scripts
  • Use password managers: Store encryption passwords securely
  • Different passwords: Don’t reuse passwords across multiple encrypted files

Key Management

# Generate GPG key pair for asymmetric encryption
gpg --gen-key

# List keys
gpg --list-keys

# Encrypt file for specific recipient (asymmetric)
gpg -e -r recipient@email.com file.txt

# Decrypt file encrypted for you
gpg -d file.txt.gpg -o file.txt

Secure File Deletion

# Securely delete original after encryption
shred -vfz -n 10 original.txt

# Or use GPG to delete original automatically
gpg -c --delete original.txt

Encrypting Directories

Using EncFS (Encrypted Filesystem)

# Install encfs
sudo apt install encfs  # Debian/Ubuntu
sudo yum install encfs  # RHEL/CentOS

# Create encrypted directory
encfs ~/.encrypted ~/decrypted

# Mount encrypted directory
encfs ~/.encrypted ~/decrypted

# Unmount
fusermount -u ~/decrypted

Using LUKS for Full Directory Encryption

# Create encrypted container
dd if=/dev/zero of=encrypted.img bs=1M count=100
cryptsetup luksFormat encrypted.img

# Open and mount
cryptsetup luksOpen encrypted.img myencrypted
mkfs.ext4 /dev/mapper/myencrypted
mount /dev/mapper/myencrypted /mnt/encrypted

Encrypting Files for Email Transmission

When sending sensitive files via email, encryption prevents unauthorized access even if emails are intercepted:

# Encrypt file for email attachment
gpg -c --armor sensitive-report.pdf

# Creates sensitive-report.pdf.asc (ASCII-armored, email-safe)

# Recipient decrypts
gpg -d sensitive-report.pdf.asc -o sensitive-report.pdf

Verifying File Integrity

Create Checksums

# Create SHA256 checksum before encryption
sha256sum original.txt > original.txt.sha256

# After decryption, verify integrity
sha256sum -c original.txt.sha256

GPG Signatures

# Sign file (proves authenticity)
gpg --sign document.txt

# Encrypt and sign
gpg -c --sign confidential.txt

# Verify signature
gpg --verify document.txt.gpg

Troubleshooting Common Issues

GPG Password Prompt Issues

# If GUI prompt fails, force terminal prompt
export GPG_TTY=$(tty)
gpg -c file.txt

# Use pinentry for terminal
echo "pinentry-program /usr/bin/pinentry-tty" >> ~/.gnupg/gpg-agent.conf
gpgconf --reload gpg-agent

Permission Denied Errors

# Fix GPG directory permissions
chmod 700 ~/.gnupg
chmod 600 ~/.gnupg/*

Frequently Asked Questions

What is the difference between symmetric and asymmetric encryption in GPG?

Symmetric encryption (gpg -c) uses the same password for encryption and decryption – simple but requires secure password sharing. Asymmetric encryption uses public/private key pairs: you encrypt with recipient’s public key, they decrypt with their private key – more secure for multi-party communication, no password sharing needed. Use symmetric for personal file encryption, asymmetric when sending encrypted files to others.

Can I recover an encrypted file if I forget the password?

No, if you forget the password for a GPG or OpenSSL encrypted file, the data is permanently inaccessible. Strong encryption is designed to be unbreakable without the correct password. Always keep secure backups of passwords in a password manager, and consider keeping unencrypted backups of critical files in secure physical locations like safes.

Is GPG encryption secure enough for sensitive business data?

Yes, GPG uses industry-standard encryption algorithms (AES-256, RSA-4096) trusted by governments and corporations worldwide. When combined with strong passwords (16+ characters), GPG-encrypted files are considered computationally infeasible to crack with current technology. Ensure you use current GPG versions and strong passphrases for maximum security.

How do I encrypt files without the GUI password prompt?

Use the –batch and –passphrase-fd options for non-interactive encryption: “echo ‘password’ | gpg –batch –passphrase-fd 0 -c file.txt”. For scripts, store the password in a secure file with restricted permissions (chmod 600) and use –passphrase-file. Be cautious as password exposure in scripts creates security risks.

What is the .gpg vs .asc file extension?

The .gpg extension indicates binary GPG-encrypted files – smaller and faster but not email-safe. The .asc extension (created with –armor option) produces ASCII-armored text files – larger but safe for email transmission and can be viewed in text editors. Use .gpg for local storage, .asc for email or text-based transmission.

Can encrypted files be detected as malicious by antivirus software?

Sometimes encrypted files trigger antivirus warnings because malware often uses encryption to hide malicious code. GPG and OpenSSL encrypted files are legitimate, but some security software may flag them. Whitelist your encrypted directories in antivirus settings, or use file extensions that security software recognizes (.gpg, .asc, .enc).

How do I encrypt an entire directory tree efficiently?

Create a tar archive first, then encrypt the single archive file: “tar czf – /path/to/directory | gpg -c > directory.tar.gz.gpg”. This encrypts the entire directory structure in one operation. To decrypt: “gpg -d directory.tar.gz.gpg | tar xzf -“. This approach is faster and more manageable than encrypting individual files.

Should I delete the original file after encryption?

Yes, for sensitive data. Use secure deletion tools like shred: “shred -vfz -n 10 original.txt” to overwrite the file before deletion, preventing recovery. Regular deletion (rm) doesn’t actually erase data from disk. Some GPG frontends offer automatic secure deletion after encryption. Always verify the encrypted file can be decrypted before deleting the original.

What encryption algorithm should I use for maximum security?

AES-256 is the current industry standard and provides excellent security. Use “gpg -c –cipher-algo AES256 file.txt” to explicitly specify it. For OpenSSL, use “openssl enc -aes-256-cbc”. While AES-128 is also secure, AES-256 provides a larger security margin. Avoid older algorithms like DES, 3DES, or RC4 which have known vulnerabilities.

Can I encrypt files on one Linux distribution and decrypt on another?

Yes, GPG and OpenSSL are cross-platform and cross-distribution compatible. Files encrypted on Ubuntu can be decrypted on CentOS, Fedora, or even Windows/macOS with GPG installed. Ensure both systems use compatible GPG versions (GPG 2.x is current standard). The encrypted file format is standardized, making it portable across any system with GPG support.

Conclusion

File encryption in Linux is straightforward yet powerful, with GPG and OpenSSL providing enterprise-grade security for personal and professional use. Whether encrypting individual files for email transmission, protecting sensitive documents on shared systems, or securing entire directory trees, Linux encryption tools offer flexible, reliable solutions. By following best practicesÒ€”using strong passwords, verifying encrypted files before deleting originals, and understanding the difference between symmetric and asymmetric encryptionÒ€”you can ensure your sensitive data remains protected.

Master these encryption techniques to safeguard confidential information, comply with data protection regulations, and maintain privacy in an increasingly connected world. Encryption is not just for security professionals; it’s an essential skill for anyone handling sensitive data in the modern computing environment.

Was this article helpful?

RS

About the Author: Ramesh Sundararamaiah

Red Hat Certified Architect

Ramesh is a Red Hat Certified Architect with extensive experience in enterprise Linux environments. He specializes in system administration, DevOps automation, and cloud infrastructure. Ramesh has helped organizations implement robust Linux solutions and optimize their IT operations for performance and reliability.

Expertise: Red Hat Enterprise Linux, CentOS, Ubuntu, Docker, Ansible, System Administration, DevOps

Add Comment