Diffie-Hellman in 2 lines of perl

#!/usr/local/bin/perl -- -export-a-crypto-system-sig Diffie-Hellman-2-lines
($g,$e,$m)=@ARGV,$m||die"$0 gen exp mod\n";print`echo "16dio1[d2%Sa2/d0<X+d

Diffie-Hellman key exchange allows two parties who have not met to exchange keys securely on an unsecure communication path. Typically D-H is used to exchange a randomly generated conventional encryption key, the rest of the exchange is then encrypted with the conventional cipher. It has been used with DES, 3DES, IDEA, RC4 though basically the approach of using D-H key exchange can be used for any conventional stream or block cipher.

PGP itself operates in a similar fashion, except that PGP uses RSA for key exchange, and IDEA as the conventional cipher.

The maths for Diffie-Hellman is quite simple.

Here is an example:

We are trying to exchange a random key for communication. Say that we will be using the RC4 stream cipher as our conventional cipher. Here's the stages in the process.

Real example

You can try sending me some RC4 encrypted email, using a D-H negotiated session key.

For security (the above example is for clarity only 32 bit keys are utterly useless for security purposes) we will use 1024 bits. Here is my Diffie-Helman public key, you can have a go at negotiating a D-H key exchange and sending me some RC4 encrypted email.

I have chosen an x (which I won't be telling you this time for obvious reasons), and calculated the corresponding a as described above. Here are my D-H public key numbers:

g = 3

m = 

a =
To send me some mail you will need to generate your choice of random y as described above, and then calculate the session key s:
% dh [a] [y] [m] > s
(where [a] and [m] are the large numbers above cut and pasted in, and [y] is your large random number.) and then calculate key exchange number b:
% dh [g] [y] [m] > b
% mail adam@cypherspace.org < b
Then you compose your mail message as file "msg" and rc4 encrypt that using s as calculated above:
% cat msg | rc4 `cat s` | uuencode r r | mail adam@cypherspace.org

Comments, html bugs to me (Adam Back) at <adam@cypherspace.org>