properly match fingerprints with leading 0 bytes (https://labs.riseup.net/code/issues...
[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 $timestamp = shift;
372
373   my ($n, $e) = $key->get_key_parameters();
374
375   return
376     pack('CN', 4, $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 $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, $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 $timestamp = shift;
416
417   my $rsabody = make_rsa_pub_key_body($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   my $version = pack('C', 4);
440   # strong assertion of identity:
441   my $sigtype = pack('C', $sig_types->{positive_certification});
442   # RSA
443   my $pubkey_algo = pack('C', $asym_algos->{rsa});
444   # SHA1
445   my $hash_algo = pack('C', $digests->{sha256});
446
447   # FIXME: i'm worried about generating a bazillion new OpenPGP
448   # certificates from the same key, which could easily happen if you run
449   # this script more than once against the same key (because the
450   # timestamps will differ).  How can we prevent this?
451
452   # this environment variable (if set) overrides the current time, to
453   # be able to create a standard key?  If we read the key from a file
454   # instead of stdin, should we use the creation time on the file?
455   my $timestamp = 0;
456   if (defined $args->{timestamp}) {
457     $timestamp = ($args->{timestamp} + 0);
458   } else {
459     $timestamp = time();
460   }
461
462   my $creation_time_packet = pack('CCN', 5, $subpacket_types->{sig_creation_time}, $timestamp);
463
464
465   my $flags = 0;
466   if (! defined $args->{usage_flags}) {
467     $flags = $usage_flags->{certify};
468   } else {
469     my @ff = split(",", $args->{usage_flags});
470     foreach my $f (@ff) {
471       if (! defined $usage_flags->{$f}) {
472         die "No such flag $f";
473       }
474       $flags |= $usage_flags->{$f};
475     }
476   }
477
478   my $usage_packet = pack('CCC', 2, $subpacket_types->{usage_flags}, $flags);
479
480
481   # how should we determine how far off to set the expiration date?
482   # default is no expiration.  Specify the timestamp in seconds from the
483   # key creation.
484   my $expiration_packet = '';
485   if (defined $args->{expiration}) {
486     my $expires_in = $args->{expiration} + 0;
487     $expiration_packet = pack('CCN', 5, $subpacket_types->{key_expiration_time}, $expires_in);
488   }
489
490
491   # prefer AES-256, AES-192, AES-128, CAST5, 3DES:
492   my $pref_sym_algos = pack('CCCCCCC', 6, $subpacket_types->{preferred_cipher},
493                             $ciphers->{aes256},
494                             $ciphers->{aes192},
495                             $ciphers->{aes128},
496                             $ciphers->{cast5},
497                             $ciphers->{tripledes}
498                            );
499
500   # prefer SHA-512, SHA-384, SHA-256, SHA-224, RIPE-MD/160, SHA-1
501   my $pref_hash_algos = pack('CCCCCCCC', 7, $subpacket_types->{preferred_digest},
502                              $digests->{sha512},
503                              $digests->{sha384},
504                              $digests->{sha256},
505                              $digests->{sha224},
506                              $digests->{ripemd160},
507                              $digests->{sha1}
508                             );
509
510   # prefer ZLIB, BZip2, ZIP
511   my $pref_zip_algos = pack('CCCCC', 4, $subpacket_types->{preferred_compression},
512                             $zips->{zlib},
513                             $zips->{bzip2},
514                             $zips->{zip}
515                            );
516
517   # we support the MDC feature:
518   my $feature_subpacket = pack('CCC', 2, $subpacket_types->{features},
519                                $features->{mdc});
520
521   # keyserver preference: only owner modify (???):
522   my $keyserver_pref = pack('CCC', 2, $subpacket_types->{keyserver_prefs},
523                             $keyserver_prefs->{nomodify});
524
525   my $subpackets_to_be_hashed =
526     $creation_time_packet.
527       $usage_packet.
528         $expiration_packet.
529           $pref_sym_algos.
530             $pref_hash_algos.
531               $pref_zip_algos.
532                 $feature_subpacket.
533                   $keyserver_pref;
534
535   my $subpacket_octets = pack('n', length($subpackets_to_be_hashed));
536
537   my $sig_data_to_be_hashed =
538     $version.
539       $sigtype.
540         $pubkey_algo.
541           $hash_algo.
542             $subpacket_octets.
543               $subpackets_to_be_hashed;
544
545   my $pubkey = make_rsa_pub_key_body($rsa, $timestamp);
546   my $seckey = make_rsa_sec_key_body($rsa, $timestamp);
547
548   # this is for signing.  it needs to be an old-style header with a
549   # 2-packet octet count.
550
551   my $key_data = make_packet($packet_types->{pubkey}, $pubkey, {'packet_length'=>2});
552
553   # take the last 8 bytes of the fingerprint as the keyid:
554   my $keyid = substr(fingerprint($rsa, $timestamp), 20 - 8, 8);
555
556   # the v4 signature trailer is:
557
558   # version number, literal 0xff, and then a 4-byte count of the
559   # signature data itself.
560   my $trailer = pack('CCN', 4, 0xff, length($sig_data_to_be_hashed));
561
562   my $uid_data =
563     pack('CN', 0xb4, length($uid)).
564       $uid;
565
566   my $datatosign =
567     $key_data.
568       $uid_data.
569         $sig_data_to_be_hashed.
570           $trailer;
571
572   my $data_hash = Digest::SHA1::sha1_hex($datatosign);
573
574   my $issuer_packet = pack('CCa8', 9, $subpacket_types->{issuer}, $keyid);
575
576   my $sig = Crypt::OpenSSL::Bignum->new_from_bin($rsa->sign($datatosign));
577
578   my $sig_body =
579     $sig_data_to_be_hashed.
580       pack('n', length($issuer_packet)).
581         $issuer_packet.
582           pack('n', hex(substr($data_hash, 0, 4))).
583             mpi_pack($sig);
584
585   return
586     make_packet($packet_types->{seckey}, $seckey).
587       make_packet($packet_types->{uid}, $uid).
588         make_packet($packet_types->{sig}, $sig_body);
589 }
590
591
592 sub openpgp2ssh {
593   my $instr = shift;
594   my $fpr = shift;
595
596   if (defined $fpr) {
597     if (length($fpr) < 8) {
598       die "We need at least 8 hex digits of fingerprint.\n";
599     }
600     $fpr = uc($fpr);
601   }
602
603   my $packettag;
604   my $dummy;
605   my $tag;
606
607   my $key;
608
609   while (! eof($instr)) {
610     read($instr, $packettag, 1);
611     $packettag = ord($packettag);
612
613     my $packetlen;
614     if ( ! (0x80 & $packettag)) {
615       die "This is not an OpenPGP packet\n";
616     }
617     if (0x40 & $packettag) {
618       $tag = (0x3f & $packettag);
619       my $nextlen = 0;
620       read($instr, $nextlen, 1);
621       $nextlen = ord($nextlen);
622       if ($nextlen < 192) {
623         $packetlen = $nextlen;
624       } elsif ($nextlen < 224) {
625         my $newoct;
626         read($instr, $newoct, 1);
627         $newoct = ord($newoct);
628         $packetlen = (($nextlen - 192) << 8) + ($newoct) + 192;
629       } elsif ($nextlen == 255) {
630         read($instr, $nextlen, 4);
631         $packetlen = unpack('N', $nextlen);
632       } else {
633         # packet length is undefined.
634       }
635     } else {
636       my $lentype;
637       $lentype = 0x03 & $packettag;
638       $tag = ( 0x3c & $packettag ) >> 2;
639       if ($lentype == 0) {
640         read($instr, $packetlen, 1) or die "could not read packet length\n";
641         $packetlen = unpack('C', $packetlen);
642       } elsif ($lentype == 1) {
643         read($instr, $packetlen, 2) or die "could not read packet length\n";
644         $packetlen = unpack('n', $packetlen);
645       } elsif ($lentype == 2) {
646         read($instr, $packetlen, 4) or die "could not read packet length\n";
647         $packetlen = unpack('N', $packetlen);
648       } else {
649         # packet length is undefined.
650       }
651     }
652
653     if (! defined($packetlen)) {
654       die "Undefined packet lengths are not supported.\n";
655     }
656
657     if ($tag == $packet_types->{pubkey} ||
658         $tag == $packet_types->{pub_subkey} ||
659         $tag == $packet_types->{seckey} ||
660         $tag == $packet_types->{sec_subkey}) {
661       my $ver;
662       my $readbytes = 0;
663       read($instr, $ver, 1) or die "could not read key version\n";
664       $readbytes += 1;
665       $ver = ord($ver);
666
667       if ($ver != 4) {
668         printf(STDERR "We only work with version 4 keys.  This key appears to be version %s.\n", $ver);
669         read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
670       } else {
671
672         my $timestamp;
673         read($instr, $timestamp, 4) or die "could not read key timestamp.\n";
674         $readbytes += 4;
675         $timestamp = unpack('N', $timestamp);
676
677         my $algo;
678         read($instr, $algo, 1) or die "could not read key algorithm.\n";
679         $readbytes += 1;
680         $algo = ord($algo);
681         if ($algo != $asym_algos->{rsa}) {
682           printf(STDERR "We only support RSA keys (this key used algorithm %d).\n", $algo);
683           read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
684         } else {
685           ## we have an RSA key.
686           my $modulus = read_mpi($instr, \$readbytes);
687           my $exponent = read_mpi($instr, \$readbytes);
688
689           my $pubkey = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus, $exponent);
690           my $foundfpr = fingerprint($pubkey, $timestamp);
691
692           my $foundfprstr = Crypt::OpenSSL::Bignum->new_from_bin($foundfpr)->to_hex();
693           # left-pad with 0's to bring up to full 40-char (160-bit) fingerprint:
694           $foundfprstr = sprintf("%040s", $foundfprstr);
695
696           # is this a match?
697           if ((!defined($fpr)) ||
698               (substr($foundfprstr, -1 * length($fpr)) eq $fpr)) {
699             if (defined($key)) {
700               die "Found two matching keys.\n";
701             }
702             $key = $pubkey;
703           }
704
705           if ($tag == $packet_types->{seckey} ||
706               $tag == $packet_types->{sec_subkey}) {
707             if (!defined($key)) { # we don't think the public part of
708                                   # this key matches
709               read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
710             } else {
711               my $s2k;
712               read($instr, $s2k, 1) or die "Could not read S2K octet.\n";
713               $readbytes += 1;
714               $s2k = ord($s2k);
715               if ($s2k == 0) {
716                 # secret material is unencrypted
717                 # see http://tools.ietf.org/html/rfc4880#section-5.5.3
718                 my $d = read_mpi($instr, \$readbytes);
719                 my $p = read_mpi($instr, \$readbytes);
720                 my $q = read_mpi($instr, \$readbytes);
721                 my $u = read_mpi($instr, \$readbytes);
722
723                 my $checksum;
724                 read($instr, $checksum, 2) or die "Could not read checksum of secret key material.\n";
725                 $readbytes += 2;
726                 $checksum = unpack('n', $checksum);
727
728                 # FIXME: compare with the checksum!  how?  the data is
729                 # gone into the Crypt::OpenSSL::Bignum
730
731                 $key = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus,
732                                                                     $exponent,
733                                                                     $d,
734                                                                     $p,
735                                                                     $q);
736
737                 $key->check_key() or die "Secret key is not a valid RSA key.\n";
738               } else {
739                 print(STDERR "We cannot handle encrypted secret keys.  Skipping!\n") ;
740                 read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
741               }
742             }
743           }
744
745         }
746       }
747     } else {
748       read($instr, $dummy, $packetlen) or die "Could not skip past this packet!\n";
749     }
750   }
751
752   return $key;
753 }
754
755
756 for (basename($0)) {
757   if (/^pem2openpgp$/) {
758     my $rsa;
759     my $stdin;
760
761     my $uid = shift;
762     defined($uid) or die "You must specify a user ID string.\n";
763
764     # FIXME: fail if there is no given user ID; or should we default to
765     # hostname_long() from Sys::Hostname::Long ?
766
767
768     if (defined $ENV{PEM2OPENPGP_NEWKEY}) {
769       $rsa = Crypt::OpenSSL::RSA->generate_key($ENV{PEM2OPENPGP_NEWKEY});
770     } else {
771       $stdin = do {
772         local $/; # slurp!
773         <STDIN>;
774       };
775
776       $rsa = Crypt::OpenSSL::RSA->new_private_key($stdin);
777     }
778
779     print pem2openpgp($rsa,
780                       $uid,
781                       { timestamp => $ENV{PEM2OPENPGP_TIMESTAMP},
782                         expiration => $ENV{PEM2OPENPGP_EXPIRATION},
783                         usage_flags => $ENV{PEM2OPENPGP_USAGE_FLAGS},
784                       }
785                      );
786   }
787   elsif (/^openpgp2ssh$/) {
788       my $fpr = shift;
789       my $instream;
790       open($instream,'-');
791       binmode($instream, ":bytes");
792       my $key = openpgp2ssh($instream, $fpr);
793       if (defined($key)) {
794         if ($key->is_private()) {
795           print $key->get_private_key_string();
796         } else {
797           print "ssh-rsa ".encode_base64(openssh_pubkey_pack($key), '')."\n";
798         }
799       } else {
800         die "No matching key found.\n";
801       }
802   }
803   else {
804     die "Unrecognized keytrans call.\n";
805   }
806 }
807