Encrypt a file using gpg

From Andreida
Revision as of 11:32, 16 February 2016 by Andreas (talk | contribs) (Created page with "<User-ID> is always just enough to find the key in the key ring. == Encryption / Decryption == Create a key gpg --gen-key Encrypt the file gpg --recipient '<User-ID>' -...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

<User-ID> is always just enough to find the key in the key ring.

Encryption / Decryption

Create a key

 gpg --gen-key

Encrypt the file

 gpg --recipient '<User-ID>' --output test.gpg --encrypt test.txt

Decrypt the file

 gpg --output test.out.txt --decrypt test.gpg

Key Backup

List keys

 gpg --list-keys

Export the public key

 gpg --armor --output pubkey.txt --export '<User-ID>'

Export the private key

 gpg --armor --output private.txt --export-secret-keys '<User-ID>'

Delete Keys

Delete the private key

 gpg --delete-secret-key <User-ID>

Delete the public key

 gpg --delete-key <User-ID>

Restore Keys

Import the private (and implicit public) key

 gpg --import private.txt

Trust your own key

To remove the boring interactive questioning after the message

 There is no assurance this key belongs to the named user
gpg --edit-key <User-ID>
trust 1  (or whatever number is needed)
save

Script

The following script will take any file and encrypt it to filename + '.gpg'. You have to change the <User-ID> of course.

#!/bin/bash

# if there are too few parameters, show the syntax and exit
if [ $# -ne 1 ]; then
  echo Syntax: $0 \<file\>
  echo Example: $0 /opt/Backups/BackupEtcAndHome.tar.gz
  exit 1
fi

# if the file does not exist, show an error and exit
if [ ! -e $1 ]; then
  echo Error: file $1 does not exist !
  exit 2
fi

Source=$1
Target=$1.gpg

echo -n Removing target $Target...
rm -f $Target
echo ok

echo -n Encrypting $Source to $Target...
gpg --recipient 'User-ID' --output $Target --encrypt $Source
echo ok

echo -n changing attributes...
chmod 600 $Target
echo ok

ls -lh $Target