Tag: scripts

PSP Movie Encoding

If you want to encode video to PSP format on Linux install ffmpeg and try this:

ffmpeg -i my_home_movie.mpg -f psp -r 29.97 -b 512k -ar 24000 -ab 64k -s 368x208 my_home_movie.mp4

Or if you prefer the other style you can try this:

ffmpeg -i my_home_movie.mpg -f psp -r 29.97 -b 512k -ar 24000 -ab 64k -s 320x240 my_home_movie.mp4

For me the first option is the best.  But naturally its up to your taste as to what you prefer and you can muck about with all of the options but these worked well enough for me.


To Mail a File Elegantly – Python or Perl?

People fixate on particular languages and stir hot debates over the entrails of code compared in the cold hard light of a walk through but is the debate over which language is better worth even the energy of debate any more? Take for example a trivial task such as regularly sending a file via email, a simple administrative task. There was a day in which Java didn’t have Java mail and Perl didn’t have its elegant MIME::lite so the only way to so things was via bash and some mail client written in C. But today every language has mail client tools built into it, in fact so many of the modern languages like Python and PHP have so many solutions to the common problems worked out in them is there any point over personal preference?

Personally I still like to gut the compared implementations like a fish and have a look. Partly because these questions are fascinating to me, partly because I like to take the opportunity to wind up the religious proponents of each language, and partly because I prefer to gut code rather than fish. Your code might stink but never as much as fish guts.

There is one other reason that I like to perform comparative code autopsies and that is to get into the mind of the people it affects. So lets talk Python, the language of all things Gnome and Perl the language of the data miner. These two languages and their communities are very interesting. Our gnomes have only been, comparatively, around for a short period of time and tend to look at code for code’s sake. Yes python might be the language of GUIs and building blocks are important; but they’re not everything. On the other hand we have the gristled old data miners emerging from their day at the data face deep in their mine chiselling out useful information from the earthy data buried three fathoms deep in some odious data warehouse. They’re all about getting the task done, producing the goods for their team and finding the information that their users want. So there’s the stage a constructive pantheon of building block gnomes and the old data hounds seeking useful information.

Let’s set a comparison task now and see how their favourite tools stake up. But we have to be careful. If we choose a GUI task the miners will go on strike; alternatively if we select a data parsing task the gnomes will sit on their treasures and grump. Hence the task that I’ve chosen favours neither group, it’s stupidly simple and it is something any system administrator can relate to; creating a script to email a file. The rules of the game are:

  • Each language must use its own mail tool set, no invoking mutt or any other such tool,
  • For input the script must take all of the information: SMTP email server address, from address, to address, and fully qualified file name from the command line,
  • A help text and minimal useful input validation along with error reporting must be included, but trivially,
  • Only one file at a time is to be handled,
  • Simple text in the body and subject must be hard coded in the script body with the exception of file name,
  • The file must be in an attachment, not in-line Base64 and should be able to be of any type, not necessarily specified by MIME type,
  • This task is stupidly simple, so so should the script be.

So to the breach!  First up the Perl.

#!/usr/bin/perl

use MIME::Lite;

$address=$ARGV[0];
$from=$ARGV[1];
$to=$ARGV[2];
$path=$ARGV[3];

$usage='filemail.pl smtp from to path';
die "Usage: $usage\n" if $#ARGV != 3;

( $dir, $name ) = ($path=~m/(.*)[\\\/](.+)/) ? ( $1, $2 ) : ( undef, $path );
open FILE, $path or die "Could not find file '$path'";
close FILE;

$msg = MIME::Lite->new(
    From     => $from,
    To       => $to,
    Cc       => '',
    Subject  => "File '$name'.",
    Data     => "Please find file '$name' attached."
  );

$msg->attach(
    Type        =>  'application/octet-stream',
    Path        =>  $path,
    Filename    =>  $name,
    Disposition =>  'attachment'
  ); 

MIME::Lite->send('smtp', $address, Timeout=>60);
$msg->send();

Next the Python.

#!/usr/bin/python

import os
import smtplib
import email
import email.mime.text
import email.mime.multipart
import optparse

# set up the command line parser and grab the args
parser = optparse.OptionParser(usage="""\
Send file attached to a MIME message.

Usage: %prog [options]
""")
parser.add_option('-a', '--address',
                  type='string', action='store', metavar='ADDRESS',
                  help="""Address of the SMTP server (required)""")
parser.add_option('-p', '--path',
                  type='string', action='store', metavar='PATH',
                  help="""Location of the file to send (required)""")
parser.add_option('-s', '--sender',
                  type='string', action='store', metavar='SENDER',
                  help='The value of the From: header (required)')
parser.add_option('-r', '--recipient',
                  type='string', action='append', metavar='RECIPIENT',
                  default=[], dest='recipients',
                  help='A To: header value (at least one required)')
opts, args = parser.parse_args()

# bomb with help if the required arguments are not present
if not opts.path \
        or not opts.sender \
        or not opts.recipients \
        or not opts.address \
        or not opts.path:
    parser.print_help()
    os.sys.exit(1)
if not os.path.isfile(opts.path):
    print 'File \'' + opts.path + '\' not found.'
    os.sys.exit(1)

# create the enclosing (msg) message
filename = opts.path.split('/')[-1]
msg = email.mime.multipart.MIMEMultipart()
msg['Subject'] = 'File \'' + filename + '\'.'
msg['To'] = ', '.join(opts.recipients)
msg['From'] = opts.sender
msg.preamble = 'Please find file \'' + filename + '\' attached.\n'

# message body
body = email.mime.multipart.MIMEMultipart('alternative')
body.attach(email.mime.text.MIMEText('Please find file \'' + filename + '\' attached.\n'))
body.attach(email.mime.text.MIMEText('Please find file \'' + filename + '\' attached.\n', 'html'))

msg.attach(body)

# attach the file
fp = open(opts.path, 'rb')
att = email.mime.base.MIMEBase('application', 'octet-stream')
att.set_payload(fp.read())
fp.close()
email.encoders.encode_base64(att)
att.add_header('Content-Disposition', 'attachment', filename=filename)

msg.attach(att)

# send the message
composed = msg.as_string()
s = smtplib.SMTP(opts.address)
s.sendmail(opts.sender, opts.recipients, composed)
s.quit()

Now for my taste there is no contest. I find myself in the company of wrinkled old miners covered in the dust of ages of data mining experience and dutiful determination. So why did I choose to use the tool of gnomes? Well several reasons really but first lets just make a couple of observations about the code. Neither good or bad, just observations. Then we’ll come back to the decision over choice and the ultimate answer to the ultimate question, is there really any difference of substance between the languages?

  • For shear size Perl has the smaller amount of code.
  • In detail Python is very revealing, it shows some of the nature and structure of the thing that it is building.
  • Considering layout Perl provides us with more opportunities to lay things out for current and future reviewers.
  • In terms of handiness Python provides a wonderful tool for handling standard command line parsing and help generation.
  • Results from either implementation are near enough to identical where it counts.

Now the key here in this list is the last item, where it counts, in other words the results of running both of these scripts, is near enough to identical. The function for which these scripts was written has been achieved within the rules of the game. The only things that we are left debating are the non-functional aspects of the implementation, size, process description, navigation and flexibility. To me the elegance of the Perl solution simply trumps the Python implementation cold. But that’s personal preference based on ascetics. Python proponents will argue that the elegance of Perl is simply the result of a library which could quite easily have been created in Python. Which is true. But you see it isn’t. If it was it would have been. To expand; this is symptomatic of the perspective of the two different communities. Those playing with perls of wisdom know that scripting is all about getting things done, so they ask themselves what is the minimum amount of information that I can get away with providing to get the results that I want. Speed to an end. Focus on results. In the garden of code we find our gnomes building beautiful frameworks which can be used for all sorts of things, generalisation is the key, making it work for the world. Of course you can do mail with Python, but we would rather have a flexible solution for the masses than elegant solutions for the minorities.

To answer the question is there any point to using one language over another other than preference? No. However if you are sitting in a camp of gnomes armed to the teeth with pick axes then all hail the magnificent Python, but if you don’t want to get a shovel through your head after a day in the data mines polish your Perl. At the end of the day there is no real big difference between all of these languages, and if you are like me and sit in the camp with gnomes and miners just pick the one that means the least work for you. In my case it was just more expedient to deploy Python.


Python and pyinotify

A friend of mine posted a really good article over at blogspot about using pyinotify; after reading one of the comments there I started playing around with it. So if you want the original have a look at David Latham’s original post. I’ve simplified the code just a little to get to the essence of pyinotify. Incidentally if you’re working from Fedora like I am you might like to ‘yum install python-inotify*‘ and confirm that the module and documentation are installed. Here’s the base version.


#!/usr/bin/python

import os
import pyinotify

m = pyinotify.WatchManager()
notifier = pyinotify.Notifier(m, pyinotify.ProcessEvent())
m.add_watch('/tmp/', pyinotify.ALL_EVENTS, rec=True)

while True:

    try:
        notifier.process_events()
        if notifier.check_events():
            notifier.read_events()

    except KeyboardInterrupt:
        notifier.stop()
        break


It works really well for this example but has one generally unwelcome side effect. It also blocks on the ‘notifier.check_events()‘ call. A blocking call is not really what you want in an event loop so it doesn’t really work too well for the core of the application. However this is overcome very simply by adding the three extra parameters defining the wait timing of the ‘pyinotify.Notifier(m, pyinotify.ProcessEvent(), 0, 0, 10)‘. In this case the block is turned to a 10 second wait courtesy of the last parameter as shown in the next code snippet below. In an application event loop you would use a value of 0 meaning that the call would not block at all.


#!/usr/bin/python

import os
import pyinotify

m = pyinotify.WatchManager()
notifier = pyinotify.Notifier(m, pyinotify.ProcessEvent(), 0, 0, 10)
m.add_watch('/tmp/', pyinotify.ALL_EVENTS, rec=True)

while True:

    try:
        notifier.process_events()
        if notifier.check_events():
            notifier.read_events()

    except KeyboardInterrupt:
        notifier.stop()
        break


In this case the default event handler just prints XML formatted event lines to stdout. But there’s just one more unexpected side effect. You may find there are a few timing issues and how do you get the notification back to the main thread? But more on that later.


Random Passwords

Most of the time the best way of generating passwords is by using ‘passphrases’ which you can remember. But in this day and age of having a unique password for everything this approach is not always practical. For most users the temptation to generate a really secure password and then use it everywhere is just too much. Its not necessarily the remembering aspect of the equation either; it can take a lot just to generate a good secure password in the first place. Especially when each site that you visit or application that you use has similar but crucially differing requirements. For me the best way to store multiple passwords is in a secured store using a regularly rolled key, in my case PGP encrypted files.

To easily generate a random password in Linux all you need to do is:

  'dd if=/dev/urandom count=1 4> /dev/null | uuencode -m - \
  | sed -ne 2p | cut -c-16'

Note that this does rely on you having /dev/urandom, uuencode, sed and cut available on your system. Which in my case generated the following output:

  [user@blackbox ~]$ dd if=/dev/urandom count=1 4> /dev/null \
  | uuencode -m - | sed -ne 2p | cut -c-16
  1+0 records in
  1+0 records out
  512 bytes (512 B) copied, 0.000223 seconds, 2.3 MB/s
  fQ6XFnhsNWbeMtph

The password generated in this case is of course ‘fQ6XFnhsNWbeMtph’, a pain to remember for sure but very secure. A slight alteration allows for a number of passwords to be generated:

  'for ((n=0;n<10;n++)); do head -c16 /dev/urandom | uuencode -m - \
  | sed -ne 2p | cut -c-8; done'

Lists of passwords are good in the odd case where the generated password may not contain quite the flavour of included characters that you were looking for. They’re often good too when you need to roll a bunch of passwords at once or if you’re setting up a number of systems at the same time. Note the alteration in password length as set by the cut tool. There’s also a change to using head to read the random data too. Here’s an example of a set of passwords generated by the command above:

  [user@blackbox ~]$ for ((n=0;n<10;n++)); do head -c16 /dev/urandom \
  | uuencode -m -| sed -ne 2p | cut -c-8; done
  x41jVgKc
  vC+IxVLU
  xkzOfyVu
  5WwEWEat
  Ymw4C52m
  BQ5Gtcjj
  ByRqTEY
  CO79z599
  VJlcIzU7
  3mJ1F3b8

Apart from this there are a number of other things that you can do with the passwords; but these have mostly to do with the characters generated. So for example if you wanted to generate 16 digit pins you could use some variant of the following:

  head -c16 /dev/urandom | od -t u8 | awk '{ print $2 }' | cut -c-16

Naturally you could add in a grep statement to the earlier commands to do something similar by capturing only numeric characters. But such a method is statistically inefficient due to the small number of digits in the earlier streams. Other cases, for example removing the non-alpha-numeric characters could be better suited for grep filtering. Quite naturally I’ve left this as an exercise for the reader as I don’t need that right now. Here’s an example execution of the pin generation command:

  [user@blackbox ~]$ head -c16 /dev/urandom | od -t u8 \
  | awk '{ print $2 }' | cut -c-16
  9815394141245590

One significant observation is that there are many statements to be found that are critical of using a random number generator to generate password data. Normally the arguments are based around the fact that automata are easily replicated and hence the passwords generated may be weak. The flaw in this argument is that the methods shown here are not intended to be infallible, just accountably strong, and in general passwords are always fallible. It’s just a question of educated guessing. However one last word, always be sure that your passwords are vetted in sample against some standard of strength and protect your generation mechanism.

Its a dangerous world out there, take care of your passwords with good policy and procedure.


Simple GPG





Introduction

This article discusses the methods of creating and using PGP keys and the GPG application for the encryption, decryption and signing of data. It is not intended to be a complete in-depth reference just a technical overview or quick reference to PGP/GPG. Most of the keystrokes that a user needs to enter have been highlighted in red. If you need an in depth reference please see the GNU Privacy Guard (GPG) Handbook.



Index

Introduction
Index
OpenPGP Overview
Encryption / Decryption
Digital Signatures
Encrypting, Signing, Sending and Decrypting Data
Using a Public Key to Encrypt Data
Using a Private Key to Sign Data
Using a Public Key to Verify a Signature
Using a Private Key to Decrypt Data
Creating, Exporting and Importing a Public/Private Key Pair
Creating a Key Pair
Exporting a Public Key
Importing a Public Key
Signing a Public Key
Backing Up Keys to a File
Exporting a Private Key
Importing a Private Key
Key Deletion and Revocation
Generating a Revocation Certificate
Importing a Revocation Certificate
Deleting a Key from the Keyring
Acronym Definitions
Links




OpenPGP Overview

OpenPGP is the standard of secure data exchange defined in the IETF RFC 4880. Essentially the standard calls for the generation of a pair of keys: one private the other public.



Encryption / Decryption

Data can be encrypted under either the public or the private key and then decrypted under the private key. The idea is then that if you wish people to be able to securely transfer data to you then you need to provide them with your public key to encrypt under and when you receive the encrypted data you can decrypt it using your private key. Note that data that has been encrypted under the public key can only be decrypted under the private key.



Digital Signatures

Message integrity, in other words detection of message alteration, is implicit in the encryption/decryption process. However PGP can also be used to confirm plain text message integrity to a high level too. The sender generates a signature using the RSA or DSA algorithms and the sender’s private key. Then the receiver then uses the sender’s public key to verify the signature against the received document. This goes some way towards verifying the sender too – dependent on the sender not sharing their private key.




Encrypting, Signing, Sending and Decrypting Data

Transmitting data securely is a multiple step process, some of which are optional. A complete scenario follows, the signature steps are optional and the transmission of data may be either pick-up or drop-off by either party as per their security and procedure policies. Naturally the key exchange component only needs to happen once or as dictated by your security policy or if a key compromise is detected.





The key exchange:

  1. The receiver: generates a private / public key pair in their PGP tool.
  2. The receiver: exports the public key from the receiver’s key store to text.
  3. The receiver: sends the public key to the sender.
  4. The sender: signs the receiver’s public key and imports it into the sender’s key store.


  1. The sender: generates a private / public key pair in their PGP tool.
  2. The sender: exports the public key from the sender’s key store to text.
  3. The sender: sends the public key to the receiver.
  4. The receiver: signs the sender’s public key and imports it into the receiver’s key store.





The data exchange:

  1. The sender: encrypts the data to be sent with the receiver’s public key.
  2. The sender: generates a signature against the encrypted data using the sender’s private key.
  3. The sender: sends both the signature and the encrypted data to the receiver.


  1. The receiver: verifies the received signature against the received encrypted data using the sender’s public key.
  2. The receiver: decrypts the received encrypted data using the receiver’s private key.




Using a Public Key to Encrypt Data

To use a public key to encrypt data you must first install the key into the tool. Graphical tools such as GPG4Win use a GUI to do this. On Redhat you can do this using the gpg command line tool. It is recommended that when you import the public key that you sign it to say that you have authenticated its integrity. To encrypt a data file using a particular private key you use the following command ‘gpg –out encrypted_secrets –encrypt unencrypted_file‘. Naturally this is a manual process, if you want to include it in an automated script you can use the command like this ‘gpg -e -o $file.pgp -r $gpg_recipient $file‘ obviously from a bash script.



[userx@blackbox ~]$ gpg –out encrypted_secrets –encrypt unencrypted_file
You did not specify a user ID. (you may use “-r”)

Current recipients:

Enter the user ID. End with an empty line: userx@companyx.co.nz

Current recipients:
2048g/5BD870E6 2008-01-09 “userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>”

Enter the user ID. End with an empty line:
[userx@blackbox ~]$ ls
Desktop encrypted_secrets rhn_updates unencrypted_file
[userx@blackbox ~]$





Using a Private Key to Sign Data

When a sender needs to send encrypted data the sender has the option of signing the encrypted data. Signing the data allows the receiver to confirm that the message was sent by the sender as long as the sender is the only one who has access to the sender’s private key. This is an optional step and may be applied to the raw data before the encryption step or more likely to the encrypted data so that the receiver can verify the integrity of the transmitted data before decrypting it.



[userx@blackbox ~]$ gpg –sign encrypted_secrets

You need a passphrase to unlock the secret key for
user: “Frederick Jones (local key for signing imported keys with among other things) <frederick.jones@acustomer.co.nz>”
1024-bit DSA key, ID C77D9B6F, created 2008-01-08

Enter passphrase: Enter your pass phrase here.

[userx@blackbox ~]$ ls
Desktop encrypted_secrets encrypted_secrets.gpg rhn_updates unencrypted_file
[userx@blackbox ~]$


Once the file has been signed the generated gpg file contains both the file contents and the signature, so you only need to send the gpg file to the recipient. There are many variations on this, for example the signature could be contained in a seperate file, the signature could be in plain text, there are switches to assist you in including this process in scripts, etc. However this is the simplest and most practical way of signing a binary file for transport.



Using a Public Key to Verify a Signature

When a receiver receives a signature along with encrypted data the receiver has the option of verifying the signature provided using the sender’s public key. Verification must be against the data that was signed, either the encrypted or the unencrypted data, sometimes for the pedantic, both. But the order must be arranged and shared prior to attempting verification.



[userx@blackbox ~]$ gpg –output secrets –decrypt encrypted_secrets.gpg
gpg: Signature made Sat 10 May 2008 03:47:16 PM NZST using DSA key ID C77D9B6F
gpg: Good signature from “Frederick Jones (local key for signing imported keys with among other things) <frederick.jones@acustomer.co.nz>”
[userx@blackbox ~]$ ls
Desktop encrypted_secrets.gpg rhn_updates secrets tmp
[userx@blackbox ~]$





Using a Private Key to Decrypt Data

Decrypting a file is almost as straight forward as encrypting one. You just need the additional passphrase value that was used during the creating of the private key. Naturally the command for decrypting files can also be used in a batch file; an example of which is ‘gpg –batch –no-tty –passphrase-fd 0 -o “$file.txt” -d $file‘. The following illustrates the manual decryption of a file.



[userx@blackbox ~]$ gpg –output secrets –decrypt encrypted_secrets

You need a passphrase to unlock the secret key for
user: “userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>”
2048-bit ELG-E key, ID 5BD870E6, created 2008-01-09 (main key ID F16BE872)

Enter passphrase: Enter your pass phrase here.

gpg: encrypted with 2048-bit ELG-E key, ID 5BD870E6, created 2008-01-09
“userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>”
[userx@blackbox ~]$






Creating, Exporting and Importing a Public / Private Key Pair

Creating a public/private key pair can be achieved using a number of tools. The keys can then be exported, imported and used in different applications as required by you security policy and process. In this section we will use GnuPG on Redhat Linux to create a key pair. You can do all of the following using an unprivileged user account.



Creating a Private Key

To create a private key you need to run ‘gpg –gen-key‘. If the gpg utility has not been used before on the account it may simply create the environment that it needs to run and exit. If so just issue the same command again to start generating the key. The following is a transcript of the process with the user’s keystrokes in red where they show up on the console.

Note that during this run the entropy on the system was not significant so the process halted at one point waiting for the system to get busy again so that it could generate more random data. The best way to do generate entropy is to simply open another session on the system and do something like browse man pages or use the network for something. Basically the random number generation part of the process relies on the random interactions of the system to generate a good standard of random data and make the generated key harder to attack.

Following generation of a new key you should always back it up, generate a revocation certificate and store them according to your security policy.



[userx@blackbox ~]$ gpg –gen-key
gpg (GnuPG) 1.4.5; Copyright (C) 2006 Free Software Foundation, Inc.
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions. See the file COPYING for details.

Please select what kind of key you want:
(1) DSA and Elgamal (default)
(2) DSA (sign only)
(5) RSA (sign only)
Your selection? 1

DSA keypair will have 1024 bits.
ELG-E keys may be between 1024 and 4096 bits long.
What keysize do you want? (2048) 2048
Requested keysize is 2048 bits
Please specify how long the key should be valid.
0 = key does not expire
<n> = key expires in n days
<n>w = key expires in n weeks
<n>m = key expires in n months
<n>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) <heinrichh@duesseldorf.de>”

Real name: userx
Email address: userx@companyx.co.nz
Comment: Practice key for testing with, not to be used in production.
You selected this USER-ID:
“userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>”

Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O
You need a Passphrase to protect your secret key.

Enter passphrase: You will not see this pass phrase appear in the console.
Repeat passphrase: You will not see it here either, this is the same phrase as on the last line.

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 284 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: /home/userx/.gnupg/trustdb.gpg: trustdb created
gpg: key F16BE872 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 1024D/F16BE872 2008-01-09
Key fingerprint = 990C 1FF2 07B9 223D 0B09 60C3 0427 9D7F F16B E872
uid userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>
sub 2048g/5BD870E6 2008-01-09

[userx@blackbox ~]$


That’s all that needs to happen to create the private key. It will be stored on the local key ring so if you need to move it to another machine you will need to export the key on this one and import it on the other. A listing of the keys on the key ring can be generated by using the command ‘gpg –list-keys’.



[userx@blackbox ~]$ gpg –list-keys
/home/userx/.gnupg/pubring.gpg
———————————
pub 1024D/F16BE872 2008-01-09
uid userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>
sub 2048g/5BD870E6 2008-01-09

[userx@blackbox ~]$





Exporting a Public Key

Next we need to generate the public key that you can distribute to the senders to encrypt data with. To create a public key simply use the command ‘gpg –armor –export userx@companyx.co.nz > mc.pk’ to generate a file with the text version of the public key in it. If you don’t redirect the output to a file it will end up on the console and you can cut and paste it from there.



[userx@blackbox ~]$ gpg –armor –export userx@companyx.co.nz
—–BEGIN PGP PUBLIC KEY BLOCK—–
Version: GnuPG v1.4.5 (GNU/Linux)


mQGiBEgjxzsRBADnsVogDhA+9yp67iPpFPO8BBn23UHzqohDuu1JbQipuALydsBf
JfRbwtCiXkQTENjYMUZigLFAt7NvvgSZL/HddQ/4f2uIoBMu5i/gai4PIslQMXTC
z5nKadB/cKemJSmk5Mkz8r28YbWbaqlWAWpWcz74NkvU1jbcdTyPMWSf4wCg59vl

Radv1oNxFvxls4vExF0hvNXl5KjM8Cknc/WhQDnDg1i9UX5okd00qPvbyoQpulCL
AZs/NalFv4hJBBgRAgAJBQJII8dCAhsMAAoJEAQnnX/xa+hy2M4An09qaadS2lPI
DYKXIH4yoCiMXiJcAJ9F1ssEm/hb+rE970NljxIkxQQtHQ==
=WJYH
—–END PGP PUBLIC KEY BLOCK—–
[userx@blackbox ~]$





Importing a Public Key

You can import any old public key into your keystore for use. Normally the public key is a simple block of text, as seen above. For this example we have copied the text into a file named ‘mcdc1.pk‘. To import the public key the command is ‘gpg –import-key filename‘. The following shows: a list of the keys in the store before import, the import command, and a listing of the keys in the store following the import command.



[userx@blackbox ~]$ gpg –list-keys
/home/userx/.gnupg/pubring.gpg
———————————
pub 1024D/C77D9B6F 2008-01-08
uid Frederick Jones (local key for signing imported keys with among other things) <frederick.jones@acustomer.co.nz>
sub 2048g/514D3AE9 2008-01-08

[userx@blackbox ~]$ gpg –import mcdc1.pk
gpg: key F16BE872: public key “userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>” imported
gpg: Total number processed: 1
gpg: imported: 1
[userx@blackbox ~]$ gpg –list-keys
/home/userx/.gnupg/pubring.gpg
———————————
pub 1024D/C77D9B6F 2008-01-08
uid Frederick Jones (local key for signing imported keys with among other things) <frederick.jones@acustomer.co.nz>
sub 2048g/514D3AE9 2008-01-08

pub 1024D/F16BE872 2008-01-09
uid userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>
sub 2048g/5BD870E6 2008-01-09

[userx@blackbox ~]$





Signing a Public Key

Before using a public key it is advisable to sign it with your own private key. Signing a key adds it to your trusted keys keystore. Essentially it says that the key is to be trusted because you have verified its integrity and authenticity. Then the key can often be used by applications without them having to prompt for confirmation of its authenticity. Signing a key is a little more involved than importing it, but it is still a very straight foward process. Notice that in this example the first attempt at remembering the passphrase failed but the next attempt passed. Also note that there was already a private key against which to sign the public key. The last part is just a key listing for completeness sake.



[userx@blackbox ~]$ gpg –edit-key userx@companyx.co.nz
gpg (GnuPG) 1.4.5; Copyright (C) 2006 Free Software Foundation, Inc.
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions. See the file COPYING for details.

pub 1024D/F16BE872 created: 2008-01-09 expires: never usage: SC
trust: unknown validity: unknown
sub 2048g/5BD870E6 created: 2008-01-09 expires: never usage: E
[ unknown] (1). userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>

Command> fpr
pub 1024D/F16BE872 2008-01-09 userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>
Primary key fingerprint: 990C 1FF2 07B9 223D 0B09 60C3 0427 9D7F F16B E872

Command> sign

pub 1024D/F16BE872 created: 2008-01-09 expires: never usage: SC
trust: unknown validity: unknown
Primary key fingerprint: 990C 1FF2 07B9 223D 0B09 60C3 0427 9D7F F16B E872

userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>

Are you sure that you want to sign this key with your
key “Frederick Jones (local key for signing imported keys with among other things) <frederick.jones@acustomer.co.nz>” (C77D9B6F)

Really sign? (y/N) y

You need a passphrase to unlock the secret key for
user: “Frederick Jones (local key for signing imported keys with among other things) <frederick.jones@acustomer.co.nz>”
1024-bit DSA key, ID C77D9B6F, created 2008-01-08

gpg: Invalid passphrase; please try again …

You need a passphrase to unlock the secret key for
user: “Frederick Jones (local key for signing imported keys with among other things) <frederick.jones@acustomer.co.nz>”
1024-bit DSA key, ID C77D9B6F, created 2008-01-08

Command> quit
Save changes? (y/N) y
[userx@blackbox ~]$ gpg –list-keys
gpg: checking the trustdb
gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model
gpg: depth: 0 valid: 1 signed: 1 trust: 0-, 0q, 0n, 0m, 0f, 1u
gpg: depth: 1 valid: 1 signed: 0 trust: 1-, 0q, 0n, 0m, 0f, 0u
/home/userx/.gnupg/pubring.gpg
———————————
pub 1024D/C77D9B6F 2008-01-08
uid Frederick Jones (local key for signing imported keys with among other things) <frederick.jones@acustomer.co.nz>
sub 2048g/514D3AE9 2008-01-08

pub 1024D/F16BE872 2008-01-09
uid userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>
sub 2048g/5BD870E6 2008-01-09

[userx@blackbox ~]$






Backing Up Keys to File

Backing up keys is a simple export to file process. It then needs to be securely stored somewhere. When it needs to be restored its a simple import operation to get it back in to the keyring. Needless to say the security of the private keys is of utmost importance to preseve the integrity of the cryptographic processes; in other words, store them securely and don’t loose them. Backup and restore of public keys have already been covered in a previous section so they are not covered here.



Exporting a Private Key

Exporting a private key to a file is a one line event and results in a UTF-8 text file that should be stored securely then the text file deleted securely from the machine that generated it. The command is ‘gpg –armor –output filename.key –export-secret-keys keyid‘, to get the keyid you can use the command ‘gpg –list-secret-keys‘.

You can additionally encrypt the generated file using a command like

gpg –amor –export-secret-keys keyid | gpg –amor –symmetric

–output filename.key‘ and use a passphrase to protect the key. Naturally you will need to supply and keep a secure passphrase for archival purposes. This should all be determined in your security policy. It is possible to additionally sign this file too, but you may end up in a catch-22 loop if you aren’t careful with your trust hierarchy.



[userx@blackbox ~]$ gpg –list-secret-keys
/home/userx/.gnupg/secring.gpg
———————————
sec 1024D/F16BE872 2008-01-09
uid userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>
ssb 2048g/5BD870E6 2008-01-09

[userx@blackbox ~]$ gpg –armor –export-secret-keys F16BE872 | gpg –armor –symmetric –output userx-secret.key
Enter passphrase: Put your pass phrase here, don’t forget it!
Repeat passphrase: Repeat your pass phrase here, store it securely for when you want to restore the key!
[userx@blackbox ~]$ ls
Desktop encrypted_secrets.gpg userx-secret.key rhn_updates secrets tmp
[userx@blackbox ~]$ cat userx-secret.key
—–BEGIN PGP MESSAGE—–
Version: GnuPG v1.4.5 (GNU/Linux)


jA0EAwMCDMzqGkiI4nVgyer8LfE22zw9q7hRnR7xNB/RDEUyDtkjChCv3KYEmn/q
6BZuoGSDQA9nC+zaCaJnhbKc8ACsPKg5ymMR3mGOBp1x4N4rbIQsy9iGK6tnw9B6
TnYWCaf2ltrMMCbB9pwnvQdRiFqb7rX/ojppeCuG9/ZjwGXfYesyBIqhZjTrQ+BD

BmI+pEF9btI/pP+kDCHt0L0oS25Ph6rltCQuEXKWOPtWtC2Ph2OS/PgUAvZ0IJu6
/UsgUX10vIWJ8GZUerdEJRqO8NKG1DRtzUXV0ibK0lJlpY+begTJllWNfS0zOOWh
hLMlskxgvh47nrI6RenCed3tEynPDS5HkAf0LoiIRP/dWQnhjMg=
=UcOA
—–END PGP MESSAGE—–
[userx@blackbox ~]$





Importing a Private Key

Restoring a key from backup is very straight forward. In this case we will just look at restoring an encrypted key, so you need the backed up file and pass phrase. To restore the key you can use the following command, supplying the pass phrase when asked, ‘gpg –decrypt filename.gpg | gpg –import‘.



[userx@blackbox ~]$ gpg –list-secret-keys
/home/userx/.gnupg/secring.gpg
———————————
sec 1024D/C77D9B6F 2008-01-08
uid Frederick Jones (local key for signing imported keys with among other things) <frederick.jones@acustomer.co.nz>
ssb 2048g/514D3AE9 2008-01-08

[userx@blackbox ~]$ man gpg
[userx@blackbox ~]$ gpg –list-secret-keys
/home/userx/.gnupg/secring.gpg
———————————
sec 1024D/C77D9B6F 2008-01-08
uid Frederick Jones (local key for signing imported keys with among other things) <frederick.jones@acustomer.co.nz>
ssb 2048g/514D3AE9 2008-01-08

[userx@blackbox ~]$ gpg –decrypt userx-private.gpg | gpg –import
gpg: CAST5 encrypted data
Enter passphrase: Enter your passphrase here.
gpg: CAST5 encrypted data
gpg: encrypted with 1 passphrase
gpg: WARNING: message was not integrity protected
gpg: key F16BE872: secret key imported
gpg: key F16BE872: “userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>” not changed
gpg: Total number processed: 1
gpg: unchanged: 1
gpg: secret keys read: 1
gpg: secret keys imported: 1
[userx@blackbox ~]$ gpg –list-secret-keys
/home/userx/.gnupg/secring.gpg
———————————
sec 1024D/C77D9B6F 2008-01-08
uid Frederick Jones (local key for signing imported keys with among other things) <frederick.jones@acustomer.co.nz>
ssb 2048g/514D3AE9 2008-01-08

sec 1024D/F16BE872 2008-01-09
uid userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>
ssb 2048g/5BD870E6 2008-01-09

[userx@blackbox ~]$






Key Termination

When your keys become compromised or simply need to be retired or removed there are two options: deletion, and revocation. The difference is that deletion means you can no longer use that certificate on the machine that the key has been removed from, whereas revocation means that the key can still be used for verifying and decrypting previously created artifacts. What is used is determined by your security policy.



Generating a Revocation Certificate

Under normal circumstances you should generate a revokation certificate for each new key as you generate the key. As with most other generation operations this is quite simple. To generate a revokation certificate simply use the following command. Note that the generated certificate should be secured in the same way that your private keys are. Note that this example dumps the cert to screen, you need to capture it to file to be useful.



[userx@blackbox ~]$ gpg –list-secret-keys
/home/userx/.gnupg/secring.gpg
———————————
sec 1024D/F16BE872 2008-01-09
uid userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>
ssb 2048g/5BD870E6 2008-01-09

[userx@blackbox ~]$ gpg –armor –gen-revoke F16BE872

sec 1024D/F16BE872 2008-01-09 userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>

Create a revocation certificate for this key? (y/N) y
Please select the reason for the revocation:
0 = No reason specified
1 = Key has been compromised
2 = Key is superseded
3 = Key is no longer used
Q = Cancel
(Probably you want to select 1 here)
Your decision? 0
Enter an optional description; end it with an empty line:
> Default revoke generated with keys.
>
Reason for revocation: No reason specified
Default revoke generated with keys.
Is this okay? (y/N) y

You need a passphrase to unlock the secret key for
user: “userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>”
1024-bit DSA key, ID F16BE872, created 2008-01-09

Enter passphrase: Enter your pass phrase here.

Revocation certificate created.

Please move it to a medium which you can hide away; if Mallory gets
access to this certificate he can use it to make your key unusable.
It is smart to print this certificate and store it away, just in case
your media become unreadable. But have some caution: The print system of
your machine might store the data and make it available to others!
—–BEGIN PGP PUBLIC KEY BLOCK—–
Version: GnuPG v1.4.5 (GNU/Linux)
Comment: A revocation certificate should follow

iGwEIBECACwFAkgnrnclHQBEZWZhdWx0IHJldm9rZSBnZW5lcmF0ZWQgd2l0aCBr
ZXlzLgAKCRAEJ51/8WvockshAJ9ewkZfGPwGVP5Omf8bzMARxe6DBwCbBAi5ZAsL
9wb0CxITviZbCwJo2TQ=
=QddC
—–END PGP PUBLIC KEY BLOCK—–
[userx@blackbox ~]$





Importing a Revocation Certificate

Using a revokation certificate is as simple as importing it into the keyring. Use the following command ‘gpg –import filename‘.



[userx@blackbox ~]$ gpg –list-secret-keys
/home/userx/.gnupg/secring.gpg
———————————
sec 1024D/F16BE872 2008-01-09
uid userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>
ssb 2048g/5BD870E6 2008-01-09

[userx@blackbox ~]$ gpg –import revoke.crt
gpg: key F16BE872: “userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>” revocation certificate imported
gpg: Total number processed: 1
gpg: new key revocations: 1
gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model
gpg: depth: 0 valid: 1 signed: 1 trust: 0-, 0q, 0n, 0m, 0f, 1u
gpg: depth: 1 valid: 1 signed: 0 trust: 1-, 0q, 0n, 0m, 0f, 0u
[userx@blackbox ~]$ gpg –list-secret-keys
/home/userx/.gnupg/secring.gpg
———————————
sec 1024D/F16BE872 2008-01-09
uid userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>
ssb 2048g/5BD870E6 2008-01-09

[userx@blackbox ~]$ gpg –edit-key F16BE872
gpg (GnuPG) 1.4.5; Copyright (C) 2006 Free Software Foundation, Inc.
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions. See the file COPYING for details.

Secret key is available.

This key was revoked on 2008-01-12 by DSA key F16BE872 userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>
pub 1024D/F16BE872 created: 2008-01-09 revoked: 2008-01-12 usage: SC
trust: unknown validity: revoked
This key was revoked on 2008-01-12 by DSA key F16BE872 userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>
sub 2048g/5BD870E6 created: 2008-01-09 revoked: 2008-01-12 usage: E
[ revoked] (1). userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>

Command> quit
[userx@blackbox ~]$





Deleting a Key

Some times you need to delete a key. This is very simple, just use the command ‘gpg –delete-secret-key keyid‘ or alternatively ‘gpg –delete-key keyid‘.



[userx@blackbox ~]$ gpg –list-secret-keys
/home/userx/.gnupg/secring.gpg
———————————
sec 1024D/C77D9B6F 2008-01-08
uid Frederick Jones (local key for signing imported keys with among other things) <frederick.jones@acustomer.co.nz>
ssb 2048g/514D3AE9 2008-01-08

sec 1024D/F16BE872 2008-01-09
uid userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>
ssb 2048g/5BD870E6 2008-01-09

[userx@blackbox ~]$ gpg –delete-secret-key F16BE872
gpg (GnuPG) 1.4.5; Copyright (C) 2006 Free Software Foundation, Inc.
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions. See the file COPYING for details.

sec 1024D/F16BE872 2008-01-09 userx (Practice key for testing with, not to be used in production.) <userx@companyx.co.nz>

Delete this key from the keyring? (y/N) y
This is a secret key! – really delete? (y/N) y
[userx@blackbox ~]$ gpg –list-secret-keys
/home/userx/.gnupg/secring.gpg
———————————
sec 1024D/C77D9B6F 2008-01-08
uid Frederick Jones (local key for signing imported keys with among other things) <frederick.jones@acustomer.co.nz>
ssb 2048g/514D3AE9 2008-01-08

[userx@blackbox ~]$






Definitions

PGP - Pretty Good Privacy: an application for the encryption and decryption of data.
RSA - Rivest Shamir Adleman algorithm: the first algorithm known to be suitable for signing as well as encryption.
FIPS - Federal Information Processing Standard: publicly announced standards developed by the United States Federal Government.
DSA - Digital Signature Algorithm: a United States Federal Government standard or FIPS for digital signatures.
IETF - Internet Engineering Task Force: open standards organisation working with W3C and ISO/IEC for Internet standards.
OpenPGP aka RFC 4880 - IETF OpenPGP Message Format: latest revision of the PGP standard.
GPG aka GnuPG - GNU Privacy Guard: an RFC 4880 compliant encryption and decryption application that replaces PGP.




Links

GnuPG: Home Page
(http://gnupg.org/)

GPG4Win
(http://www.gpg4win.org/)

GNU_Privacy_Guard: Wikipedia
(http://en.wikipedia.org/wiki/GNU_Privacy_Guard)

GNU Privacy Guard Handbook
(http://www.gnupg.org/gph/en/manual.html)

Pretty Good Privacy: Wikipedia
(http://en.wikipedia.org/wiki/Pretty_Good_Privacy)

GPG/PGP Basics
(http://aplawrence.com/Basics/gpg.html)

Creating and Managing Keys: WLUG
(http://www.wlug.org.nz/GPG/PGPNotes)

Open Skills OpenPGP Tutorial
(http://wiki.openskills.org/OpenSkills/OpenPGP)

Ubuntu GnuPrivacyGuardHowTo
(https://help.ubuntu.com/community/GnuPrivacyGuardHowto)

Email with Mutt and GPG

(http://codesorcery.net/old/mutt/mutt-gnupg-howto)


Copyright © 1996-2010 Code Snips. All rights reserved.
iDream theme by Templates Next | Powered by WordPress