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