Jan 122013
 

Today i return to the topic of encryption and security and in particular I’ll show how to simply encrypt a file with GnuPG, this can be really usefull to encrypt a single file where you have your passwords or some personal information that you want to keep safer.

GNU Privacy Guard (GnuPG or GPG) is a GPL Licensed alternative to the PGP suite of cryptographic software. GnuPG is compliant with RFC 4880, which is the current IETF standards track specification of OpenPGP. Current versions of PGP (and Veridis’ Filecrypt) are interoperable with GnuPG and other OpenPGP-compliant systems.

This software is frequently integrated with mail client so it can sign, crypt or do both actions on the mail you send and receive, and now we’ll see how to use it on the command line to encrypt a file.



Solution 1 – Encrypt with a simmetric key

This is the easiest way to encrypt a file, you use a “password” to encrypt the file and when you want to decrypt the cyphertext you have to give the same password.
The key, in practice, represent a shared secret between two or more parties that can be used to maintain a private information, in general this solution is as good as the password you choose, can be a good solution to send a document via email and communicate the password with another media (telephone, instant message, chat).

In this example I’ll use a simple file, mysecretdocument.txt that contains secret 1234

mint-desktop tmp # cat mysecretdocument.txt
secret 1234

Now we can use the gpg option -c (or --symmetric) to encrypt with a symmetric cipher using a passphrase. The default symmetric cipher used is CAST5, but may be chosen with the --cipher-algo option:

mint-desktop tmp # gpg -c mysecretdocument.txt 
gpg: directory `/root/.gnupg' created
gpg: new configuration file `/root/.gnupg/gpg.conf' created
gpg: WARNING: options in `/root/.gnupg/gpg.conf' are not yet active during this run
gpg: keyring `/root/.gnupg/pubring.gpg' created

This was my first use of gpg on this computer and so it has created the directory /root/.gnupg and some files, this is normal if you have never used gpg, also it asked me twice for a passphradse, once that i typed it 2 times it create the new file, now I’ve on that directory the new encrypted file:

mint-desktop tmp # ls -alrt
-rw-r--r--  1 root   root      12 Jan 10 23:13 mysecretdocument.txt
-rw-r--r--  1 root   root      67 Jan 10 23:14 mysecretdocument.txt.gpg

And we can do a cat of the the new file, to verify that it has been encrypted, the default behaviour is to keep the same file name of the original and add at the end the suffix .gpg, :

mint-desktop tmp # cat mysecretdocument.txt.gpg

This will show a bunch of unprintable characters, this is fine.

Now we can keep our secret file and delete the one in plain text, or send it via email and once we need to see our secret again, we can use the command:

mint-desktop tmp # gpg -d mysecretdocument.txt.gpg
gpg: keyring `/root/.gnupg/secring.gpg' created
gpg: CAST5 encrypted data
gpg: gpg-agent is not available in this session
gpg: encrypted with 1 passphrase
secret 1234
gpg: WARNING: message was not integrity protected

gpg with the -d option print the output directly on standard output, to write it to a file you can use the gpg option -o outputfile.txt:

mint-desktop tmp # gpg -o mynewfile.txt -d mysecretdocument.txt.gpg 
mint-desktop tmp # ls -l my*
-rw-r--r-- 1 root root 12 Jan 10 23:37 mynewfile.txt
-rw-r--r-- 1 root root 12 Jan 10 23:13 mysecretdocument.txt
-rw-r--r-- 1 root root 67 Jan 10 23:14 mysecretdocument.txt.gpg

Solution 2 – Encrypt with a public key

There is also another approach to encryption, GPG allows you to use public-private key encryption to encrypt and decrypt files on Windows and Linux. The benefit of public-private key encryption is that you can keep your public key out in the open, and use it from anywhere to encrypt files. Once encrypted with the public key, those files can only be decrypted with the private key.

So in the example we will adopt a system that will use a certificate that consists of two distinct keys, one private and one public.

The private key should remain exclusively in the hands of the owner of the certificate.
The owner will use it to decrypt files that are sent to him, that can now be sent also with insecure protocols (email, ftp, http upload)

The public key can be distributed to the whole world, without incurring in any risk of danger. It will be used to encrypt files addressed to the owner of the certificate, only the owner of the related private key can decrypt that file.

The public key can be distributed to anyone without any control. The fact that it falls into foreign hands will not constitute any danger. The greatest attention should be given exclusively to the private key, which must remain strictly in the hands of the legitimate owners.

As first thing, you must generate a public/private keypair. This keypair is generated with the --gen-key option of gpg:

$ gpg --gen-key
gpg (GnuPG) 1.4.11; Copyright (C) 2010 Free Software Foundation, Inc.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
 
Please select what kind of key you want:
   (1) RSA and RSA (default)
   (2) DSA and Elgamal
   (3) DSA (sign only)
   (4) RSA (sign only)
Your selection? 1
RSA keys may be between 1024 and 4096 bits long.
What keysize do you want? (2048) 4096
Requested keysize is 4096 bits
Please specify how long the key should be valid.
         0 = key does not expire
        = key expires in n days
      w = key expires in n weeks
      m = key expires in n months
      y = key expires in n years
Key is valid for? (0) 0
Key does not expire at all
Is this correct? (y/N) y
 
You need a user ID to identify your key; the software constructs the user ID
from the Real Name, Comment and Email Address in this form:
    "Heinrich Heine (Der Dichter) "
 
Real name: Linuxaria admin
Email address: admin@linuxaria.com
Comment: 
You selected this USER-ID:
    "Linuxaria admin "
 
Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? o
You need a Passphrase to protect your secret key.
 
gpg: gpg-agent is not available in this session
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
 
Not enough random bytes available.  Please do some other work to give
the OS a chance to collect more entropy! (Need 26 more bytes)
...........+++++
........+++++
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
gpg: key A7B8B4DD marked as ultimately trusted
public and secret key created and signed.
 
gpg: checking the trustdb
gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model
gpg: depth: 0  valid:   1  signed:   0  trust: 0-, 0q, 0n, 0m, 0f, 1u
pub   4096R/A7B8B4DD 2013-01-11
      Key fingerprint = AF7B 310A 57FF 0524 91A6  E483 83F7 FE98 A7B8 B4DD
uid                  Linuxaria admin 
sub   4096R/E427331B 2013-01-11

In this example I’ve created a RSA key 4096 bits long and set as user ID for the key which consists of the real name, e-mail address and optionally a comment “Linuxaria admin “, i can verify the new keys with the options --list-keys and --list-secret-keys

mint-desktop ~ # gpg --list-keys; 
/root/.gnupg/pubring.gpg
------------------------
pub   4096R/A7B8B4DD 2013-01-11
uid                  Linuxaria admin 
sub   4096R/E427331B 2013-01-11
 
mint-desktop ~ # gpg --list-secret-keys
/root/.gnupg/secring.gpg
------------------------
sec   4096R/A7B8B4DD 2013-01-11
uid                  Linuxaria admin 
ssb   4096R/E427331B 2013-01-11

 


Encrypt with the puclic key

And now we can encrypt a file with our public key, in real life you’ll send your public key via email, or publish it on a website so the others can do this command:

gpg -e -r admin@linuxaria.com mysecretdocument.txt

Once again we’ll have a new file with name mysecretdocument.txt.gpg, but much bigger than the one of the former example, this time we have used the options -e and -r that stands for:

-e Encrypt data.
-r Encrypt for user id name. If this option or –hidden-recipient is not specified, GnuPG asks for the user-id unless –default-recipient is given.

Decrypt with the private key

To decrypt the file you can use the options -d and -o that we have used also in the former example:

mint-desktop tmp # gpg -d mysecretdocument.txt.gpg -o myfile.txt
 
You need a passphrase to unlock the secret key for
user: "Linuxaria admin <admin @linuxaria.com>"
4096-bit RSA key, ID E427331B, created 2013-01-11 (main key ID A7B8B4DD)
 
gpg: gpg-agent is not available in this session
gpg: encrypted with 4096-bit RSA key, ID E427331B, created 2013-01-11
      "Linuxaria admin </admin><admin @linuxaria.com>"
</admin>

This command will create the file myfile.txt with our clear contents

Importing new keys

To be able to encrypt files for others you’ll have to import their public keys into your keyring, and the others will do the same for your public key, to import a key, run:

	gpg --import KEYFILE

When importing a public key onto another machine, you may have configure gpg to trust the key. Otherwise, when you use the key to do encryption, you may see a prompt like this:

	It is NOT certain that the key belongs to the person named
	in the user ID.  If you *really* know what you are doing,
	you may answer the next question with yes.
 
	Use this key anyway? (y/N)

To trust the key, run:

	gpg --edit-key NAME

GPG will output some information, and show a line like:

	trust: undefined     validity: unknown

You will be at a console, and you have to type “trust”:

	Command> trust 
	Please decide how far you trust this user to correctly verify other users' keys
	(by looking at passports, checking fingerprints from different sources, etc.)
 
	  1 = I don't know or won't say
	  2 = I do NOT trust
	  3 = I trust marginally
	  4 = I trust fully
	  5 = I trust ultimately
	  m = back to the main menu
 
	Your decision? 5
	Do you really want to set this key to ultimate trust? (y/N) y

Type “quit” to quit. If you run gpg --edit-key NAME again, you will see a line as below, which means the key is now trusted.

	trust: ultimate      validity: ultimate

Reference :
Gnu Privacy Guard (GnuPG) Mini Howto
Notes for using GPG to encrypt and decrypt backup files
Encrypting and decrypting files with GnuPG

Popular Posts:

Flattr this!

  8 Responses to “How to easily encrypt a file with GPG on Linux”

  1. Gia’ il fatto che il tutto viene fatto come root, la dice lunga…

  2. $ ccrypt [file]
    $ ccrypt -R [directory]

    $ ccrypt -d [file]
    $ ccrypt -d -R [directory]

  3. wow, thanks for this clear article! now i can learn how to use GPG. excellent article! keep up the good work you’re doing!

  4. Grazie mille, sei stato utilissimo, complimenti per la chiarezza e la completezza!!! Bravo!

  5. Can it possible to get the count the record of encryted (.gpg) file without decryt the file in linux ?

  6. Hi,
    Is it possible to encrypt only part of file via gpg. For example, say I have file test.txt and and it has below content

    USERNAME=system
    PASSWORD=passw0rd

    I know we can encrypt the complete test.txt with gpg but can I encrypt only password inside the test.txt and keep everything as it is?

    Regards,
    Anish

  7. Great, very helpfull!!!!!

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

*