fix rounding issue. Thanks, Richard K Darst!
[monkeysphere.git] / src / keytrans / pem2openpgp
1 #!/usr/bin/perl -w -T
2
3 # pem2openpgp: take a PEM-encoded RSA private-key on standard input, a
4 # User ID as the first argument, and generate an OpenPGP secret key
5 # and certificate from it.
6
7 # WARNING: the secret key material *will* appear on stdout (albeit in
8 # OpenPGP form) -- if you redirect stdout to a file, make sure the
9 # permissions on that file are appropriately locked down!
10
11 # Usage:
12
13 # pem2openpgp 'ssh://'$(hostname -f) < /etc/ssh/ssh_host_rsa_key | gpg --import
14
15 # Authors:
16 #  Jameson Rollins <jrollins@finestructure.net>
17 #  Daniel Kahn Gillmor <dkg@fifthhorseman.net>
18
19 # Started on: 2009-01-07 02:01:19-0500
20
21 # License: GPL v3 or later (we may need to adjust this given that this
22 # connects to OpenSSL via perl)
23
24 use strict;
25 use warnings;
26 use File::Basename;
27 use Crypt::OpenSSL::RSA;
28 use Crypt::OpenSSL::Bignum;
29 use Crypt::OpenSSL::Bignum::CTX;
30 use Digest::SHA1;
31 use MIME::Base64;
32 use POSIX;
33
34 ## make sure all length() and substr() calls use bytes only:
35 use bytes;
36
37 my $old_format_packet_lengths = { one => 0,
38                                   two => 1,
39                                   four => 2,
40                                   indeterminate => 3,
41 };
42
43 # see RFC 4880 section 9.1 (ignoring deprecated algorithms for now)
44 my $asym_algos = { rsa => 1,
45                    elgamal => 16,
46                    dsa => 17,
47                    };
48
49 # see RFC 4880 section 9.2
50 my $ciphers = { plaintext => 0,
51                 idea => 1,
52                 tripledes => 2,
53                 cast5 => 3,
54                 blowfish => 4,
55                 aes128 => 7,
56                 aes192 => 8,
57                 aes256 => 9,
58                 twofish => 10,
59               };
60
61 # see RFC 4880 section 9.3
62 my $zips = { uncompressed => 0,
63              zip => 1,
64              zlib => 2,
65              bzip2 => 3,
66            };
67
68 # see RFC 4880 section 9.4
69 my $digests = { md5 => 1,
70                 sha1 => 2,
71                 ripemd160 => 3,
72                 sha256 => 8,
73                 sha384 => 9,
74                 sha512 => 10,
75                 sha224 => 11,
76               };
77
78 # see RFC 4880 section 5.2.3.21
79 my $usage_flags = { certify => 0x01,
80                     sign => 0x02,
81                     encrypt_comms => 0x04,
82                     encrypt_storage => 0x08,
83                     encrypt => 0x0c, ## both comms and storage
84                     split => 0x10, # the private key is split via secret sharing
85                     authenticate => 0x20,
86                     shared => 0x80, # more than one person holds the entire private key
87                   };
88
89 # see RFC 4880 section 4.3
90 my $packet_types = { pubkey_enc_session => 1,
91                      sig => 2,
92                      symkey_enc_session => 3,
93                      onepass_sig => 4,
94                      seckey => 5,
95                      pubkey => 6,
96                      sec_subkey => 7,
97                      compressed_data => 8,
98                      symenc_data => 9,
99                      marker => 10,
100                      literal => 11,
101                      trust => 12,
102                      uid => 13,
103                      pub_subkey => 14,
104                      uat => 17,
105                      symenc_w_integrity => 18,
106                      mdc => 19,
107                    };
108
109 # see RFC 4880 section 5.2.1
110 my $sig_types = { binary_doc => 0x00,
111                   text_doc => 0x01,
112                   standalone => 0x02,
113                   generic_certification => 0x10,
114                   persona_certification => 0x11,
115                   casual_certification => 0x12,
116                   positive_certification => 0x13,
117                   subkey_binding => 0x18,
118                   primary_key_binding => 0x19,
119                   key_signature => 0x1f,
120                   key_revocation => 0x20,
121                   subkey_revocation => 0x28,
122                   certification_revocation => 0x30,
123                   timestamp => 0x40,
124                   thirdparty => 0x50,
125                 };
126
127
128 # see RFC 4880 section 5.2.3.1
129 my $subpacket_types = { sig_creation_time => 2,
130                         sig_expiration_time => 3,
131                         exportable => 4,
132                         trust_sig => 5,
133                         regex => 6,
134                         revocable => 7,
135                         key_expiration_time => 9,
136                         preferred_cipher => 11,
137                         revocation_key => 12,
138                         issuer => 16,
139                         notation => 20,
140                         preferred_digest => 21,
141                         preferred_compression => 22,
142                         keyserver_prefs => 23,
143                         preferred_keyserver => 24,
144                         primary_uid => 25,
145                         policy_uri => 26,
146                         usage_flags => 27,
147                         signers_uid => 28,
148                         revocation_reason => 29,
149                         features => 30,
150                         signature_target => 31,
151                         embedded_signature => 32,
152                        };
153
154 # bitstring (see RFC 4880 section 5.2.3.24)
155 my $features = { mdc => 0x01
156                };
157
158 # bitstring (see RFC 4880 5.2.3.17)
159 my $keyserver_prefs = { nomodify => 0x80
160                       };
161
162 ###### end lookup tables ######
163
164 # FIXME: if we want to be able to interpret openpgp data as well as
165 # produce it, we need to produce key/value-swapped lookup tables as well.
166
167
168 ########### Math/Utility Functions ##############
169
170
171 # see the bottom of page 43 of RFC 4880
172 sub simple_checksum {
173   my $bytes = shift;
174
175   return unpack("%32W*",$bytes) % 65536;
176 }
177
178 # calculate the multiplicative inverse of a mod b this is euclid's
179 # extended algorithm.  For more information see:
180 # http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm the
181 # arguments here should be Crypt::OpenSSL::Bignum objects.  $a should
182 # be the larger of the two values, and the two values should be
183 # coprime.
184
185 sub modular_multi_inverse {
186   my $a = shift;
187   my $b = shift;
188
189
190   my $origdivisor = $b->copy();
191
192   my $ctx = Crypt::OpenSSL::Bignum::CTX->new();
193   my $x = Crypt::OpenSSL::Bignum->zero();
194   my $y = Crypt::OpenSSL::Bignum->one();
195   my $lastx = Crypt::OpenSSL::Bignum->one();
196   my $lasty = Crypt::OpenSSL::Bignum->zero();
197
198   my $finalquotient;
199   my $finalremainder;
200
201   while (! $b->is_zero()) {
202     my ($quotient, $remainder) = $a->div($b, $ctx);
203
204     $a = $b;
205     $b = $remainder;
206
207     my $temp = $x;
208     $x = $lastx->sub($quotient->mul($x, $ctx));
209     $lastx = $temp;
210
211     $temp = $y;
212     $y = $lasty->sub($quotient->mul($y, $ctx));
213     $lasty = $temp;
214   }
215
216   if (!$a->is_one()) {
217     die "did this math wrong.\n";
218   }
219
220   # let's make sure that we return a positive value because RFC 4880,
221   # section 3.2 only allows unsigned values:
222
223   ($finalquotient, $finalremainder) = $lastx->add($origdivisor)->div($origdivisor, $ctx);
224
225   return $finalremainder;
226 }
227
228
229 ############ OpenPGP formatting functions ############
230
231 # make an old-style packet out of the given packet type and body.
232 # old-style  (see RFC 4880 section 4.2)
233 sub make_packet {
234   my $type = shift;
235   my $body = shift;
236   my $options = shift;
237
238   my $len = length($body);
239   my $pseudolen = $len;
240
241   # if the caller wants to use at least N octets of packet length,
242   # pretend that we're using that many.
243   if (defined $options && defined $options->{'packet_length'}) {
244       $pseudolen = 2**($options->{'packet_length'} * 8) - 1;
245   }
246   if ($pseudolen < $len) {
247       $pseudolen = $len;
248   }
249
250   my $lenbytes;
251   my $lencode;
252
253   if ($pseudolen < 2**8) {
254     $lenbytes = $old_format_packet_lengths->{one};
255     $lencode = 'C';
256   } elsif ($pseudolen < 2**16) {
257     $lenbytes = $old_format_packet_lengths->{two};
258     $lencode = 'n';
259   } elsif ($pseudolen < 2**31) {
260     ## not testing against full 32 bits because i don't want to deal
261     ## with potential overflow.
262     $lenbytes = $old_format_packet_lengths->{four};
263     $lencode = 'N';
264   } else {
265     ## what the hell do we do here?
266     $lenbytes = $old_format_packet_lengths->{indeterminate};
267     $lencode = '';
268   }
269
270   return pack('C'.$lencode, 0x80 + ($type * 4) + $lenbytes, $len).
271     $body;
272 }
273
274
275 # takes a Crypt::OpenSSL::Bignum, returns it formatted as OpenPGP MPI
276 # (RFC 4880 section 3.2)
277 sub mpi_pack {
278   my $num = shift;
279
280   my $val = $num->to_bin();
281   my $mpilen = length($val)*8;
282
283 # this is a kludgy way to get the number of significant bits in the
284 # first byte:
285   my $bitsinfirstbyte = length(sprintf("%b", ord($val)));
286
287   $mpilen -= (8 - $bitsinfirstbyte);
288
289   return pack('n', $mpilen).$val;
290 }
291
292 # takes a Crypt::OpenSSL::Bignum, returns an MPI packed in preparation
293 # for an OpenSSH-style public key format.  see:
294 # http://marc.info/?l=openssh-unix-dev&m=121866301718839&w=2
295 sub openssh_mpi_pack {
296   my $num = shift;
297
298   my $val = $num->to_bin();
299   my $mpilen = length($val);
300
301   my $ret = pack('N', $mpilen);
302
303   # if the first bit of the leading byte is high, we should include a
304   # 0 byte:
305   if (ord($val) & 0x80) {
306     $ret = pack('NC', $mpilen+1, 0);
307   }
308
309   return $ret.$val;
310 }
311
312 sub openssh_pubkey_pack {
313   my $key = shift;
314
315   my ($modulus, $exponent) = $key->get_key_parameters();
316
317   return openssh_mpi_pack(Crypt::OpenSSL::Bignum->new_from_bin("ssh-rsa")).
318       openssh_mpi_pack($exponent).
319         openssh_mpi_pack($modulus);
320 }
321
322 # pull an OpenPGP-specified MPI off of a given stream, returning it as
323 # a Crypt::OpenSSL::Bignum.
324 sub read_mpi {
325   my $instr = shift;
326   my $readtally = shift;
327
328   my $bitlen;
329   read($instr, $bitlen, 2) or die "could not read MPI length.\n";
330   $bitlen = unpack('n', $bitlen);
331   $$readtally += 2;
332
333   my $bytestoread = POSIX::floor(($bitlen + 7)/8);
334   my $ret;
335   read($instr, $ret, $bytestoread) or die "could not read MPI body.\n";
336   $$readtally += $bytestoread;
337   return Crypt::OpenSSL::Bignum->new_from_bin($ret);
338 }
339
340
341 # FIXME: genericize these to accept either RSA or DSA keys:
342 sub make_rsa_pub_key_body {
343   my $key = shift;
344   my $timestamp = shift;
345
346   my ($n, $e) = $key->get_key_parameters();
347
348   return
349     pack('CN', 4, $timestamp).
350       pack('C', $asym_algos->{rsa}).
351         mpi_pack($n).
352           mpi_pack($e);
353 }
354
355 sub make_rsa_sec_key_body {
356   my $key = shift;
357   my $timestamp = shift;
358
359   # we're not using $a and $b, but we need them to get to $c.
360   my ($n, $e, $d, $p, $q) = $key->get_key_parameters();
361
362   my $c3 = modular_multi_inverse($p, $q);
363
364   my $secret_material = mpi_pack($d).
365     mpi_pack($p).
366       mpi_pack($q).
367         mpi_pack($c3);
368
369   # according to Crypt::OpenSSL::RSA, the closest value we can get out
370   # of get_key_parameters is 1/q mod p; but according to sec 5.5.3 of
371   # RFC 4880, we're actually looking for u, the multiplicative inverse
372   # of p, mod q.  This is why we're calculating the value directly
373   # with modular_multi_inverse.
374
375   return
376     pack('CN', 4, $timestamp).
377       pack('C', $asym_algos->{rsa}).
378         mpi_pack($n).
379           mpi_pack($e).
380             pack('C', 0). # seckey material is not encrypted -- see RFC 4880 sec 5.5.3
381               $secret_material.
382                 pack('n', simple_checksum($secret_material));
383 }
384
385 # expects an RSA key (public or private) and a timestamp
386 sub fingerprint {
387   my $key = shift;
388   my $timestamp = shift;
389
390   my $rsabody = make_rsa_pub_key_body($key, $timestamp);
391
392   return Digest::SHA1::sha1(pack('Cn', 0x99, length($rsabody)).$rsabody);
393 }
394
395
396 # FIXME: handle DSA keys as well!
397 sub pem2openpgp {
398   my $rsa = shift;
399   my $uid = shift;
400   my $args = shift;
401
402   $rsa->use_sha1_hash();
403
404   # see page 22 of RFC 4880 for why i think this is the right padding
405   # choice to use:
406   $rsa->use_pkcs1_padding();
407
408   if (! $rsa->check_key()) {
409     die "key does not check";
410   }
411
412   my $version = pack('C', 4);
413   # strong assertion of identity:
414   my $sigtype = pack('C', $sig_types->{positive_certification});
415   # RSA
416   my $pubkey_algo = pack('C', $asym_algos->{rsa});
417   # SHA1
418   my $hash_algo = pack('C', $digests->{sha1});
419
420   # FIXME: i'm worried about generating a bazillion new OpenPGP
421   # certificates from the same key, which could easily happen if you run
422   # this script more than once against the same key (because the
423   # timestamps will differ).  How can we prevent this?
424
425   # this environment variable (if set) overrides the current time, to
426   # be able to create a standard key?  If we read the key from a file
427   # instead of stdin, should we use the creation time on the file?
428   my $timestamp = 0;
429   if (defined $args->{timestamp}) {
430     $timestamp = ($args->{timestamp} + 0);
431   } else {
432     $timestamp = time();
433   }
434
435   my $creation_time_packet = pack('CCN', 5, $subpacket_types->{sig_creation_time}, $timestamp);
436
437
438   my $flags = 0;
439   if (! defined $args->{usage_flags}) {
440     $flags = $usage_flags->{certify};
441   } else {
442     my @ff = split(",", $args->{usage_flags});
443     foreach my $f (@ff) {
444       if (! defined $usage_flags->{$f}) {
445         die "No such flag $f";
446       }
447       $flags |= $usage_flags->{$f};
448     }
449   }
450
451   my $usage_packet = pack('CCC', 2, $subpacket_types->{usage_flags}, $flags);
452
453
454   # how should we determine how far off to set the expiration date?
455   # default is no expiration.  Specify the timestamp in seconds from the
456   # key creation.
457   my $expiration_packet = '';
458   if (defined $args->{expiration}) {
459     my $expires_in = $args->{expiration} + 0;
460     $expiration_packet = pack('CCN', 5, $subpacket_types->{key_expiration_time}, $expires_in);
461   }
462
463
464   # prefer AES-256, AES-192, AES-128, CAST5, 3DES:
465   my $pref_sym_algos = pack('CCCCCCC', 6, $subpacket_types->{preferred_cipher},
466                             $ciphers->{aes256},
467                             $ciphers->{aes192},
468                             $ciphers->{aes128},
469                             $ciphers->{cast5},
470                             $ciphers->{tripledes}
471                            );
472
473   # prefer SHA-1, SHA-256, RIPE-MD/160
474   my $pref_hash_algos = pack('CCCCC', 4, $subpacket_types->{preferred_digest},
475                              $digests->{sha1},
476                              $digests->{sha256},
477                              $digests->{ripemd160}
478                             );
479
480   # prefer ZLIB, BZip2, ZIP
481   my $pref_zip_algos = pack('CCCCC', 4, $subpacket_types->{preferred_compression},
482                             $zips->{zlib},
483                             $zips->{bzip2},
484                             $zips->{zip}
485                            );
486
487   # we support the MDC feature:
488   my $feature_subpacket = pack('CCC', 2, $subpacket_types->{features},
489                                $features->{mdc});
490
491   # keyserver preference: only owner modify (???):
492   my $keyserver_pref = pack('CCC', 2, $subpacket_types->{keyserver_prefs},
493                             $keyserver_prefs->{nomodify});
494
495   my $subpackets_to_be_hashed =
496     $creation_time_packet.
497       $usage_packet.
498         $expiration_packet.
499           $pref_sym_algos.
500             $pref_hash_algos.
501               $pref_zip_algos.
502                 $feature_subpacket.
503                   $keyserver_pref;
504
505   my $subpacket_octets = pack('n', length($subpackets_to_be_hashed));
506
507   my $sig_data_to_be_hashed =
508     $version.
509       $sigtype.
510         $pubkey_algo.
511           $hash_algo.
512             $subpacket_octets.
513               $subpackets_to_be_hashed;
514
515   my $pubkey = make_rsa_pub_key_body($rsa, $timestamp);
516   my $seckey = make_rsa_sec_key_body($rsa, $timestamp);
517
518   # this is for signing.  it needs to be an old-style header with a
519   # 2-packet octet count.
520
521   my $key_data = make_packet($packet_types->{pubkey}, $pubkey, {'packet_length'=>2});
522
523   # take the last 8 bytes of the fingerprint as the keyid:
524   my $keyid = substr(fingerprint($rsa, $timestamp), 20 - 8, 8);
525
526   # the v4 signature trailer is:
527
528   # version number, literal 0xff, and then a 4-byte count of the
529   # signature data itself.
530   my $trailer = pack('CCN', 4, 0xff, length($sig_data_to_be_hashed));
531
532   my $uid_data =
533     pack('CN', 0xb4, length($uid)).
534       $uid;
535
536   my $datatosign =
537     $key_data.
538       $uid_data.
539         $sig_data_to_be_hashed.
540           $trailer;
541
542   my $data_hash = Digest::SHA1::sha1_hex($datatosign);
543
544   my $issuer_packet = pack('CCa8', 9, $subpacket_types->{issuer}, $keyid);
545
546   my $sig = Crypt::OpenSSL::Bignum->new_from_bin($rsa->sign($datatosign));
547
548   my $sig_body =
549     $sig_data_to_be_hashed.
550       pack('n', length($issuer_packet)).
551         $issuer_packet.
552           pack('n', hex(substr($data_hash, 0, 4))).
553             mpi_pack($sig);
554
555   return
556     make_packet($packet_types->{seckey}, $seckey).
557       make_packet($packet_types->{uid}, $uid).
558         make_packet($packet_types->{sig}, $sig_body);
559 }
560
561
562 sub openpgp2ssh {
563   my $instr = shift;
564   my $fpr = shift;
565
566   if (defined $fpr) {
567     if (length($fpr) < 8) {
568       die "We need at least 8 hex digits of fingerprint.\n";
569     }
570     $fpr = uc($fpr);
571   }
572
573   my $packettag;
574   my $dummy;
575   my $tag;
576
577   my $key;
578
579   while (! eof($instr)) {
580     read($instr, $packettag, 1);
581     $packettag = ord($packettag);
582
583     my $packetlen;
584     if ( ! (0x80 & $packettag)) {
585       die "This is not an OpenPGP packet\n";
586     }
587     if (0x40 & $packettag) {
588       $tag = (0x3f & $packettag);
589       my $nextlen = 0;
590       read($instr, $nextlen, 1);
591       $nextlen = ord($nextlen);
592       if ($nextlen < 192) {
593         $packetlen = $nextlen;
594       } elsif ($nextlen < 224) {
595         my $newoct;
596         read($instr, $newoct, 1);
597         $newoct = ord($newoct);
598         $packetlen = (($nextlen - 192) << 8) + ($newoct) + 192;
599       } elsif ($nextlen == 255) {
600         read($instr, $nextlen, 4);
601         $packetlen = unpack('N', $nextlen);
602       } else {
603         # packet length is undefined.
604       }
605     } else {
606       my $lentype;
607       $lentype = 0x03 & $packettag;
608       $tag = ( 0x3c & $packettag ) >> 2;
609       if ($lentype == 0) {
610         read($instr, $packetlen, 1) or die "could not read packet length\n";
611         $packetlen = unpack('C', $packetlen);
612       } elsif ($lentype == 1) {
613         read($instr, $packetlen, 2) or die "could not read packet length\n";
614         $packetlen = unpack('n', $packetlen);
615       } elsif ($lentype == 2) {
616         read($instr, $packetlen, 4) or die "could not read packet length\n";
617         $packetlen = unpack('N', $packetlen);
618       } else {
619         # packet length is undefined.
620       }
621     }
622
623     if (! defined($packetlen)) {
624       die "Undefined packet lengths are not supported.\n";
625     }
626
627     if ($tag == $packet_types->{pubkey} ||
628         $tag == $packet_types->{pub_subkey} ||
629         $tag == $packet_types->{seckey} ||
630         $tag == $packet_types->{sec_subkey}) {
631       my $ver;
632       my $readbytes = 0;
633       read($instr, $ver, 1) or die "could not read key version\n";
634       $readbytes += 1;
635       $ver = ord($ver);
636
637       if ($ver != 4) {
638         printf(STDERR "We only work with version 4 keys.  This key appears to be version %s.\n", $ver);
639         read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
640       } else {
641
642         my $timestamp;
643         read($instr, $timestamp, 4) or die "could not read key timestamp.\n";
644         $readbytes += 4;
645         $timestamp = unpack('N', $timestamp);
646
647         my $algo;
648         read($instr, $algo, 1) or die "could not read key algorithm.\n";
649         $readbytes += 1;
650         $algo = ord($algo);
651         if ($algo != $asym_algos->{rsa}) {
652           printf(STDERR "We only support RSA keys (this key used algorithm %d).\n", $algo);
653           read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
654         } else {
655           ## we have an RSA key.
656           my $modulus = read_mpi($instr, \$readbytes);
657           my $exponent = read_mpi($instr, \$readbytes);
658
659           my $pubkey = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus, $exponent);
660           my $foundfpr = fingerprint($pubkey, $timestamp);
661
662           my $foundfprstr = Crypt::OpenSSL::Bignum->new_from_bin($foundfpr)->to_hex();
663
664           # is this a match?
665           if ((!defined($fpr)) ||
666               (substr($foundfprstr, -1 * length($fpr)) eq $fpr)) {
667             if (defined($key)) {
668               die "Found two matching keys.\n";
669             }
670             $key = $pubkey;
671           }
672
673           if ($tag == $packet_types->{seckey} ||
674               $tag == $packet_types->{sec_subkey}) {
675             if (!defined($key)) { # we don't think the public part of
676                                   # this key matches
677               read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
678             } else {
679               my $s2k;
680               read($instr, $s2k, 1) or die "Could not read S2K octet.\n";
681               $readbytes += 1;
682               $s2k = ord($s2k);
683               if ($s2k == 0) {
684                 # secret material is unencrypted
685                 # see http://tools.ietf.org/html/rfc4880#section-5.5.3
686                 my $d = read_mpi($instr, \$readbytes);
687                 my $p = read_mpi($instr, \$readbytes);
688                 my $q = read_mpi($instr, \$readbytes);
689                 my $u = read_mpi($instr, \$readbytes);
690
691                 my $checksum;
692                 read($instr, $checksum, 2) or die "Could not read checksum of secret key material.\n";
693                 $readbytes += 2;
694                 $checksum = unpack('n', $checksum);
695
696                 # FIXME: compare with the checksum!  how?  the data is
697                 # gone into the Crypt::OpenSSL::Bignum
698
699                 $key = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus,
700                                                                     $exponent,
701                                                                     $d,
702                                                                     $p,
703                                                                     $q);
704
705                 $key->check_key() or die "Secret key is not a valid RSA key.\n";
706               } else {
707                 print(STDERR "We cannot handle encrypted secret keys.  Skipping!\n") ;
708                 read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
709               }
710             }
711           }
712
713         }
714       }
715     } else {
716       read($instr, $dummy, $packetlen) or die "Could not skip past this packet!\n";
717     }
718   }
719
720   return $key;
721 }
722
723
724 for (basename($0)) {
725   if (/^pem2openpgp$/) {
726     my $rsa;
727     my $stdin;
728
729     my $uid = shift;
730     defined($uid) or die "You must specify a user ID string.\n";
731
732     # FIXME: fail if there is no given user ID; or should we default to
733     # hostname_long() from Sys::Hostname::Long ?
734
735
736     if (defined $ENV{PEM2OPENPGP_NEWKEY}) {
737       $rsa = Crypt::OpenSSL::RSA->generate_key($ENV{PEM2OPENPGP_NEWKEY});
738     } else {
739       $stdin = do {
740         local $/; # slurp!
741         <STDIN>;
742       };
743
744       $rsa = Crypt::OpenSSL::RSA->new_private_key($stdin);
745     }
746
747     print pem2openpgp($rsa,
748                       $uid,
749                       { timestamp => $ENV{PEM2OPENPGP_TIMESTAMP},
750                         expiration => $ENV{PEM2OPENPGP_EXPIRATION},
751                         usage_flags => $ENV{PEM2OPENPGP_USAGE_FLAGS},
752                       }
753                      );
754   }
755   elsif (/^openpgp2ssh$/) {
756       my $fpr = shift;
757       my $instream;
758       open($instream,'-');
759       binmode($instream, ":bytes");
760       my $key = openpgp2ssh($instream, $fpr);
761       if (defined($key)) {
762         if ($key->is_private()) {
763           print $key->get_private_key_string();
764         } else {
765           print "ssh-rsa ".encode_base64(openssh_pubkey_pack($key), '')."\n";
766         }
767       } else {
768         die "No matching key found.\n";
769       }
770   }
771   else {
772     die "Unrecognized keytrans call.\n";
773   }
774 }
775