Jan 122013
 

Oggi ritorno al tema della crittografia e della sicurezza e, in particolare, vi mostrerò come crittografare semplicemente un file con GnuPG , questo può essere davvero utile per cifrare un singolo file in cui avete le vostre password o altre informazioni personali che si desidera mantenere più sicure.

GNU Privacy Guard (GnuPG o GPG) è un software sotto licenza GPL alternativo alla suite di software di crittografia PGP. GnuPG è compatibile con la RFC 4880, che è l’attuale IETF specifica che traccia gli standard di OpenPGP. Le attuali versioni di PGP (e Veridis Filecrypt) sono interoperabili con GnuPG e altri sistemi compatibili con OpenPGP.

Questo software è spesso integrato con client di posta in modo che firmi, cripti o faccia entrambe le azioni sulla posta elettronica inviata e ricevuta, ma adesso vedremo come usarlo sulla riga di comando per cifrare un file.

Soluzione 1 – Cifrare con una chiave simmetrica

Questo è il modo più semplice per cifrare un file, si utilizza una “password” per cifrare il file e quando si vuole decifrare il testo cifrato si deve utilizzare la stessa password.
La chiave, in pratica, rappresenta un segreto condiviso tra due o più parti che può essere utilizzata per mantenere una informazione privata, in generale, questa soluzione è buona quanto la password scelta, può essere una buona soluzione per inviare un documento tramite posta elettronica e comunicare la password con un altro supporto (telefono, messaggi istantanei, chat).

In questo esempio uso un semplice file, mysecretdocument.txtche contiene secret 1234

mint-desktop tmp # cat mysecretdocument.txt
secret 1234

Ora siamo in grado di utilizzare l’opzione gpg -c (o --symmetric) per cifrare con un algoritmo di cifratura simmetrica utilizzando una passphrase. L’algoritmo simmetrico predefinito è CAST5, ma può essere scelto con l’opzione -cipher-algo :

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

Questo era il mio primo uso di gpg su questo computer, e così ha creato la directory /root/.gnupg e alcuni file, questo è normale, se non avete mai usato gpg, dopo avermi chiesto per due volte la passphrase mi ha creato il nuovo file ed ora nelal directory ho anche questo nuovo 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

Siamo ora in grado di fare un cat del nuovo file, per verificare che sia stato cifrato, il comportamento predefinito è quello di mantenere lo stesso nome del file originale e aggiungere alla fine il suffisso .gpg :

mint-desktop tmp # cat mysecretdocument.txt.gpg

Questo mostrerà un gruppo di caratteri non stampabili, questo va bene.
Ora siamo in grado di tenere il nostro file segreto e cancellare il testo in chiaro, o inviarlo via e-mail e una volta che abbiamo bisogno di rivedere il nostro segreto, si può utilizzare il comando:

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 con l’opzione -d stampa l’output direttamente su standard output, per scriverlo in un file è possibile utilizzare l’opzione gpg -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

Soluzione 2 – Cifratura con una chiave pubblica

C’è anche un altro approccio alla crittografia, GPG consente di utilizzare una cifratura a chiave pubblica-privata per cifrare e decifrare i file su Windows e Linux. Il vantaggio della cifratua con chiave pubblico-private è che si può mantenere la vostra chiave pubblica in mezzo alla rete, e utilizzarla da qualsiasi luogo per cifrare i file. Una volta cifrati con la chiave pubblica, i file possono essere decifrati solo con la chiave privata.

Quindi, nell’esempio adotteremo un sistema che utilizza un certificato che si compone di due chiavi distinte, una pubblica e una privata.

La chiave privata dovrebbe rimanere esclusivamente nelle mani del proprietario del certificato.
Il proprietario la userà per decifrare i file che gli vengono inviati, che ora possono essere inviati anche con protocolli insicuri (e-mail, ftp, http upload)

La chiave pubblica può essere distribuita a tutto il mondo, senza incorrere in alcun rischio di pericolo. Essa verrà utilizzata per crittografare i file rivolti al titolare del certificato, solo il proprietario della relativa chiave privata è in grado di decifrare il file.

La chiave pubblica può essere distribuita a chiunque, senza alcun controllo. Il fatto che cada in mani straniere non costituisce alcun pericolo. La massima attenzione deve essere data esclusivamente alla chiave privata, che deve rimanere rigorosamente nelle mani dei legittimi proprietari.

Come prima cosa, è necessario generare una coppia di chiavi pubblica/privata. Questa coppia di chiavi viene generata con l’opzione --gen-key di 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 questo esempio ho creato una chiave RSA lunga 4096 bit ed impostato come user ID della chiave, che consiste nel vostro vero nome, indirizzo di posta elettronica e facoltativamente un commento, “Linuxaria admin “, posso verificare le nuove chiavi con le opzioni -list-keys e -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

 


Cifrare con la chiave pubblica

E ora possiamo cifrare un file con la chiave pubblica, nella vita reale si invia la propria chiave pubblica via e-mail, o la si pubblica su un sito web in modo che gli altri possano dare questo comando:

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

Ancora una volta avremo un nuovo file con nome mysecretdocument.txt.gpg, ma molto più grande di quella dell’esempio precedente, questa volta abbiamo usato le opzioni -e e -r che stanno per:

-e Cifrare i dati.
-r Cifra per destinatario nome id utente. Se non viene specificata questa opzione o –hidden-recipient, GnuPG chiede l’id utente salvo sia configurato un destinatario predefinito.

Decifrare con la chiave privata

Per decodificare il file, è possibile utilizzare le opzioni -d e -o che abbiamo usato anche nel precedente esempio:

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>

Questo comando creerà il file myfile.txt con i nostri contenuti in chiaro.

Importazione di nuove chiavi

Per essere in grado di crittografare i file e spedirli ad altri dovrete importare le loro chiavi pubbliche nel vostro portachiavi, e gli altri faranno lo stesso per la vostra chiave pubblica, per importare una chiave, eseguire:

	gpg --import KEYFILE

Quando si importa una chiave pubblica su un altro computer, potrebbe essere necessario configurare gpg per fidarsi della chiave. In caso contrario, quando si utilizza quella chiave per fare cifrare, è possibile che si visualizzi un messaggio come questo:

	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)

Per autorizzare la chiave, eseguire:

	gpg --edit-key NAME

GPG mostrerà delle informazioni, ed una riga tipo:

	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

Scrivete “quit” per uscire. Se ora eseguite ancora gpg --edit-key NAME , si vedrà una linea come quella qui sotto, il che significa che la chiave è ora attendibile.

	trust: ultimate      validity: ultimate

Riferimenti :
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 “Come criptare facilmente un file con GPG su Linux”

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

    • Scusami, ma a me non tanto.
      Che differenza c’e’ nel fare un esempio di cifratura di un file con utenza root o normale ?

  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 to GigiLaTrottola Cancel 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)

*