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.
8 # How it behaves depends on the name under which it is invoked. The
9 # implementations currently are: pem2openpgp openpgpg2pem, and
14 # pem2openpgp: take a PEM-encoded RSA private-key on standard input, a
15 # User ID as the first argument, and generate an OpenPGP secret key
16 # and certificate from it.
18 # WARNING: the secret key material *will* appear on stdout (albeit in
19 # OpenPGP form) -- if you redirect stdout to a file, make sure the
20 # permissions on that file are appropriately locked down!
24 # pem2openpgp 'ssh://'$(hostname -f) < /etc/ssh/ssh_host_rsa_key | gpg --import
29 # openpgp2pem: take a stream of OpenPGP packets containing public or
30 # secret key material on standard input, and a Key ID (or fingerprint)
31 # as the first argument. Find the matching key in the input stream,
32 # and emit it on stdout in OpenSSL-PEM format.
36 # gpg --export-secret-keys --export-options export-reset-subkey-passwd $KEYID | \
39 #For private keys, this will produce the same PKCS#1 RSAPrivateKey
40 #(PEM header: BEGIN RSA PRIVATE KEY) results as:
42 #openssl rsa -in private.pem
44 #For public keys, this will produce the same X.509
45 #SubjectPublicKeyInfo (PEM header: BEGIN PUBLIC KEY) results as:
47 #openssl rsa -in private.pem -pubout
53 # openpgp2ssh: take a stream of OpenPGP packets containing public or
54 # secret key material on standard input, and a Key ID (or fingerprint)
55 # as the first argument. Find the matching key in the input stream,
56 # and emit it on stdout in an OpenSSH-compatible format. If the input
57 # key is an OpenPGP public key (either primary or subkey), the output
58 # will be an OpenSSH single-line public key. If the input key is an
59 # OpenPGP secret key, the output will be a PEM-encoded RSA key.
63 # gpg --export-secret-subkeys --export-options export-reset-subkey-passwd $KEYID | \
64 # openpgp2ssh $KEYID | ssh-add /dev/stdin
68 # Jameson Rollins <jrollins@finestructure.net>
69 # Daniel Kahn Gillmor <dkg@fifthhorseman.net>
71 # Started on: 2009-01-07 02:01:19-0500
73 # License: GPL v3 or later (we may need to adjust this given that this
74 # connects to OpenSSL via perl)
79 use Crypt::OpenSSL::RSA;
80 use Crypt::OpenSSL::Bignum;
81 use Crypt::OpenSSL::Bignum::CTX;
86 ## make sure all length() and substr() calls use bytes only:
89 my $old_format_packet_lengths = { one => 0,
95 # see RFC 4880 section 9.1 (ignoring deprecated algorithms for now)
96 my $asym_algos = { rsa => 1,
101 # see RFC 4880 section 9.2
102 my $ciphers = { plaintext => 0,
113 # see RFC 4880 section 9.3
114 my $zips = { uncompressed => 0,
120 # see RFC 4880 section 9.4
121 my $digests = { md5 => 1,
130 # see RFC 4880 section 5.2.3.21
131 my $usage_flags = { certify => 0x01,
133 encrypt_comms => 0x04,
134 encrypt_storage => 0x08,
135 encrypt => 0x0c, ## both comms and storage
136 split => 0x10, # the private key is split via secret sharing
137 authenticate => 0x20,
138 shared => 0x80, # more than one person holds the entire private key
141 # see RFC 4880 section 4.3
142 my $packet_types = { pubkey_enc_session => 1,
144 symkey_enc_session => 3,
149 compressed_data => 8,
157 symenc_w_integrity => 18,
161 # see RFC 4880 section 5.2.1
162 my $sig_types = { binary_doc => 0x00,
165 generic_certification => 0x10,
166 persona_certification => 0x11,
167 casual_certification => 0x12,
168 positive_certification => 0x13,
169 subkey_binding => 0x18,
170 primary_key_binding => 0x19,
171 key_signature => 0x1f,
172 key_revocation => 0x20,
173 subkey_revocation => 0x28,
174 certification_revocation => 0x30,
180 # see RFC 4880 section 5.2.3.23
181 my $revocation_reasons = { no_reason_specified => 0,
183 key_compromised => 2,
185 user_id_no_longer_valid => 32,
188 # see RFC 4880 section 5.2.3.1
189 my $subpacket_types = { sig_creation_time => 2,
190 sig_expiration_time => 3,
195 key_expiration_time => 9,
196 preferred_cipher => 11,
197 revocation_key => 12,
200 preferred_digest => 21,
201 preferred_compression => 22,
202 keyserver_prefs => 23,
203 preferred_keyserver => 24,
208 revocation_reason => 29,
210 signature_target => 31,
211 embedded_signature => 32,
214 # bitstring (see RFC 4880 section 5.2.3.24)
215 my $features = { mdc => 0x01
218 # bitstring (see RFC 4880 5.2.3.17)
219 my $keyserver_prefs = { nomodify => 0x80
222 ###### end lookup tables ######
224 # FIXME: if we want to be able to interpret openpgp data as well as
225 # produce it, we need to produce key/value-swapped lookup tables as well.
228 ########### Math/Utility Functions ##############
231 # see the bottom of page 44 of RFC 4880 (http://tools.ietf.org/html/rfc4880#page-44)
232 sub simple_checksum {
235 return unpack("%16C*",$bytes);
239 # calculate/print the fingerprint of an openssh-style keyblob:
244 return join(':', map({unpack("H*", $_)} split(//, Digest::MD5::md5($keyblob))));
247 # calculate the multiplicative inverse of a mod b this is euclid's
248 # extended algorithm. For more information see:
249 # http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm the
250 # arguments here should be Crypt::OpenSSL::Bignum objects. $a should
251 # be the larger of the two values, and the two values should be
254 sub modular_multi_inverse {
259 my $origdivisor = $b->copy();
261 my $ctx = Crypt::OpenSSL::Bignum::CTX->new();
262 my $x = Crypt::OpenSSL::Bignum->zero();
263 my $y = Crypt::OpenSSL::Bignum->one();
264 my $lastx = Crypt::OpenSSL::Bignum->one();
265 my $lasty = Crypt::OpenSSL::Bignum->zero();
270 while (! $b->is_zero()) {
271 my ($quotient, $remainder) = $a->div($b, $ctx);
277 $x = $lastx->sub($quotient->mul($x, $ctx));
281 $y = $lasty->sub($quotient->mul($y, $ctx));
286 die "did this math wrong.\n";
289 # let's make sure that we return a positive value because RFC 4880,
290 # section 3.2 only allows unsigned values:
292 ($finalquotient, $finalremainder) = $lastx->add($origdivisor)->div($origdivisor, $ctx);
294 return $finalremainder;
298 ############ OpenPGP formatting functions ############
300 # make an old-style packet out of the given packet type and body.
301 # old-style (see RFC 4880 section 4.2)
307 my $len = length($body);
308 my $pseudolen = $len;
310 # if the caller wants to use at least N octets of packet length,
311 # pretend that we're using that many.
312 if (defined $options && defined $options->{'packet_length'}) {
313 $pseudolen = 2**($options->{'packet_length'} * 8) - 1;
315 if ($pseudolen < $len) {
322 if ($pseudolen < 2**8) {
323 $lenbytes = $old_format_packet_lengths->{one};
325 } elsif ($pseudolen < 2**16) {
326 $lenbytes = $old_format_packet_lengths->{two};
328 } elsif ($pseudolen < 2**31) {
329 ## not testing against full 32 bits because i don't want to deal
330 ## with potential overflow.
331 $lenbytes = $old_format_packet_lengths->{four};
334 ## what the hell do we do here?
335 $lenbytes = $old_format_packet_lengths->{indeterminate};
339 return pack('C'.$lencode, 0x80 + ($type * 4) + $lenbytes, $len).
344 # takes a Crypt::OpenSSL::Bignum, returns it formatted as OpenPGP MPI
345 # (RFC 4880 section 3.2)
349 my $val = $num->to_bin();
350 my $mpilen = length($val)*8;
352 # this is a kludgy way to get the number of significant bits in the
354 my $bitsinfirstbyte = length(sprintf("%b", ord($val)));
356 $mpilen -= (8 - $bitsinfirstbyte);
358 return pack('n', $mpilen).$val;
361 # takes a Crypt::OpenSSL::Bignum, returns an MPI packed in preparation
362 # for an OpenSSH-style public key format. see:
363 # http://marc.info/?l=openssh-unix-dev&m=121866301718839&w=2
364 sub openssh_mpi_pack {
367 my $val = $num->to_bin();
368 my $mpilen = length($val);
370 my $ret = pack('N', $mpilen);
372 # if the first bit of the leading byte is high, we should include a
374 if (ord($val) & 0x80) {
375 $ret = pack('NC', $mpilen+1, 0);
381 sub openssh_pubkey_pack {
384 my ($modulus, $exponent) = $key->get_key_parameters();
386 return openssh_mpi_pack(Crypt::OpenSSL::Bignum->new_from_bin("ssh-rsa")).
387 openssh_mpi_pack($exponent).
388 openssh_mpi_pack($modulus);
391 # pull an OpenPGP-specified MPI off of a given stream, returning it as
392 # a Crypt::OpenSSL::Bignum.
395 my $readtally = shift;
398 read($instr, $bitlen, 2) or die "could not read MPI length.\n";
399 $bitlen = unpack('n', $bitlen);
402 my $bytestoread = POSIX::floor(($bitlen + 7)/8);
404 read($instr, $ret, $bytestoread) or die "could not read MPI body.\n";
405 $$readtally += $bytestoread;
406 return Crypt::OpenSSL::Bignum->new_from_bin($ret);
410 # FIXME: genericize these to accept either RSA or DSA keys:
411 sub make_rsa_pub_key_body {
413 my $key_timestamp = shift;
415 my ($n, $e) = $key->get_key_parameters();
418 pack('CN', 4, $key_timestamp).
419 pack('C', $asym_algos->{rsa}).
424 sub make_rsa_sec_key_body {
426 my $key_timestamp = shift;
428 # we're not using $a and $b, but we need them to get to $c.
429 my ($n, $e, $d, $p, $q) = $key->get_key_parameters();
431 my $c3 = modular_multi_inverse($p, $q);
433 my $secret_material = mpi_pack($d).
438 # according to Crypt::OpenSSL::RSA, the closest value we can get out
439 # of get_key_parameters is 1/q mod p; but according to sec 5.5.3 of
440 # RFC 4880, we're actually looking for u, the multiplicative inverse
441 # of p, mod q. This is why we're calculating the value directly
442 # with modular_multi_inverse.
445 pack('CN', 4, $key_timestamp).
446 pack('C', $asym_algos->{rsa}).
449 pack('C', 0). # seckey material is not encrypted -- see RFC 4880 sec 5.5.3
451 pack('n', simple_checksum($secret_material));
454 # expects an RSA key (public or private) and a timestamp
457 my $key_timestamp = shift;
459 my $rsabody = make_rsa_pub_key_body($key, $key_timestamp);
461 return Digest::SHA::sha1(pack('Cn', 0x99, length($rsabody)).$rsabody);
465 # FIXME: handle DSA keys as well!
471 # strong assertion of identity is the default (for a self-sig):
472 if (! defined $args->{certification_type}) {
473 $args->{certification_type} = $sig_types->{positive_certification};
476 if (! defined $args->{sig_timestamp}) {
477 $args->{sig_timestamp} = time();
479 my $key_timestamp = $args->{key_timestamp} + 0;
481 # generate and aggregate subpackets:
485 if (! defined $args->{usage_flags}) {
486 $flags = $usage_flags->{certify};
488 my @ff = split(",", $args->{usage_flags});
489 foreach my $f (@ff) {
490 if (! defined $usage_flags->{$f}) {
491 die "No such flag $f";
493 $flags |= $usage_flags->{$f};
496 my $usage_subpacket = pack('CCC', 2, $subpacket_types->{usage_flags}, $flags);
498 # how should we determine how far off to set the expiration date?
499 # default is no expiration. Specify the timestamp in seconds from the
501 my $expiration_subpacket = '';
502 if (defined $args->{expiration}) {
503 my $expires_in = $args->{expiration} + 0;
504 $expiration_subpacket = pack('CCN', 5, $subpacket_types->{key_expiration_time}, $expires_in);
508 # prefer AES-256, AES-192, AES-128, CAST5, 3DES:
509 my $pref_sym_algos = pack('CCCCCCC', 6, $subpacket_types->{preferred_cipher},
514 $ciphers->{tripledes}
517 # prefer SHA-512, SHA-384, SHA-256, SHA-224, RIPE-MD/160, SHA-1
518 my $pref_hash_algos = pack('CCCCCCCC', 7, $subpacket_types->{preferred_digest},
523 $digests->{ripemd160},
527 # prefer ZLIB, BZip2, ZIP
528 my $pref_zip_algos = pack('CCCCC', 4, $subpacket_types->{preferred_compression},
534 # we support the MDC feature:
535 my $feature_subpacket = pack('CCC', 2, $subpacket_types->{features},
538 # keyserver preference: only owner modify (???):
539 my $keyserver_pref = pack('CCC', 2, $subpacket_types->{keyserver_prefs},
540 $keyserver_prefs->{nomodify});
543 $args->{hashed_subpackets} =
545 $expiration_subpacket.
552 return gensig($rsa, $uid, $args);
555 # FIXME: handle non-RSA keys
557 # FIXME: this currently only makes self-sigs -- we should parameterize
558 # it to make certifications over keys other than the issuer.
564 # FIXME: allow signature creation using digests other than SHA256
565 $rsa->use_sha256_hash();
567 # see page 22 of RFC 4880 for why i think this is the right padding
569 $rsa->use_pkcs1_padding();
571 if (! $rsa->check_key()) {
572 die "key does not check\n";
575 my $certtype = $args->{certification_type} + 0;
577 my $version = pack('C', 4);
578 my $sigtype = pack('C', $certtype);
580 my $pubkey_algo = pack('C', $asym_algos->{rsa});
581 # SHA256 FIXME: allow signature creation using digests other than SHA256
582 my $hash_algo = pack('C', $digests->{sha256});
584 # FIXME: i'm worried about generating a bazillion new OpenPGP
585 # certificates from the same key, which could easily happen if you run
586 # this script more than once against the same key (because the
587 # timestamps will differ). How can we prevent this?
589 # this argument (if set) overrides the current time, to
590 # be able to create a standard key. If we read the key from a file
591 # instead of stdin, should we use the creation time on the file?
592 my $sig_timestamp = ($args->{sig_timestamp} + 0);
593 my $key_timestamp = ($args->{key_timestamp} + 0);
595 if ($key_timestamp > $sig_timestamp) {
596 die "key timestamp must not be later than signature timestamp\n";
599 my $creation_time_packet = pack('CCN', 5, $subpacket_types->{sig_creation_time}, $sig_timestamp);
601 my $hashed_subs = $creation_time_packet.$args->{hashed_subpackets};
603 my $subpacket_octets = pack('n', length($hashed_subs));
605 my $sig_data_to_be_hashed =
613 my $pubkey = make_rsa_pub_key_body($rsa, $key_timestamp);
615 # this is for signing. it needs to be an old-style header with a
616 # 2-packet octet count.
618 my $key_data = make_packet($packet_types->{pubkey}, $pubkey, {'packet_length'=>2});
620 # take the last 8 bytes of the fingerprint as the keyid:
621 my $keyid = substr(fingerprint($rsa, $key_timestamp), 20 - 8, 8);
623 # the v4 signature trailer is:
625 # version number, literal 0xff, and then a 4-byte count of the
626 # signature data itself.
627 my $trailer = pack('CCN', 4, 0xff, length($sig_data_to_be_hashed));
630 pack('CN', 0xb4, length($uid)).
636 $sig_data_to_be_hashed.
639 # FIXME: handle signatures over digests other than SHA256:
640 my $data_hash = Digest::SHA::sha256_hex($datatosign);
642 my $issuer_packet = pack('CCa8', 9, $subpacket_types->{issuer}, $keyid);
644 my $sig = Crypt::OpenSSL::Bignum->new_from_bin($rsa->sign($datatosign));
647 $sig_data_to_be_hashed.
648 pack('n', length($issuer_packet)).
650 pack('n', hex(substr($data_hash, 0, 4))).
653 return make_packet($packet_types->{sig}, $sig_body);
656 # FIXME: switch to passing the whole packet as the arg, instead of the
659 # FIXME: think about native perl representation of the packets instead.
661 # Put a user ID into the $data
666 my $packetlen = shift;
669 ($tag == $packet_types->{uid}) or die "This should not be called on anything but a User ID packet\n";
671 read($instr, $dummy, $packetlen);
672 $data->{uid}->{$dummy} = {};
673 $data->{current}->{uid} = $dummy;
677 # find signatures associated with the given fingerprint and user ID.
682 my $packetlen = shift;
684 ($tag == $packet_types->{sig}) or die "No calling findsig on anything other than a signature packet.\n";
689 read($instr, $dummy, $packetlen - $readbytes) or die "Could not read in this packet.\n";
691 if ((! defined $data->{key}) ||
692 (! defined $data->{uid}) ||
693 (! defined $data->{uid}->{$data->{target}->{uid}})) {
694 # the user ID we are looking for has not been found yet.
698 # FIXME: if we get two primary keys on stdin, both with the same
699 # targetd user ID, we'll store signatures from both keys, which is
702 # the current ID is not what we're looking for:
703 return if ($data->{current}->{uid} ne $data->{target}->{uid});
705 # just storing the raw signatures for the moment:
706 push @{$data->{sigs}}, make_packet($packet_types->{sig}, $dummy);
711 # given an input stream and data, store the found key in data and
712 # consume the rest of the stream corresponding to the packet.
713 # data contains: (fpr: fingerprint to find, key: current best guess at key)
718 my $packetlen = shift;
724 read($instr, $ver, 1) or die "could not read key version\n";
729 printf(STDERR "We only work with version 4 keys. This key appears to be version %s.\n", $ver);
730 read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
735 read($instr, $key_timestamp, 4) or die "could not read key timestamp.\n";
737 $key_timestamp = unpack('N', $key_timestamp);
740 read($instr, $algo, 1) or die "could not read key algorithm.\n";
743 if ($algo != $asym_algos->{rsa}) {
744 printf(STDERR "We only support RSA keys (this key used algorithm %d).\n", $algo);
745 read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
749 ## we have an RSA key.
750 my $modulus = read_mpi($instr, \$readbytes);
751 my $exponent = read_mpi($instr, \$readbytes);
753 my $pubkey = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus, $exponent);
754 my $foundfpr = fingerprint($pubkey, $key_timestamp);
756 my $foundfprstr = Crypt::OpenSSL::Bignum->new_from_bin($foundfpr)->to_hex();
757 # left-pad with 0's to bring up to full 40-char (160-bit) fingerprint:
758 $foundfprstr = sprintf("%040s", $foundfprstr);
762 if ((!defined($data->{target}->{fpr})) ||
763 (substr($foundfprstr, -1 * length($data->{target}->{fpr})) eq $data->{target}->{fpr})) {
764 if (defined($data->{key})) {
765 die "Found two matching keys.\n";
767 $data->{key} = { 'rsa' => $pubkey,
768 'timestamp' => $key_timestamp };
772 if ($tag != $packet_types->{seckey} &&
773 $tag != $packet_types->{sec_subkey}) {
774 if ($readbytes < $packetlen) {
775 read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
780 # we don't think the public part of this key matches
781 if ($readbytes < $packetlen) {
782 read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
788 read($instr, $s2k, 1) or die "Could not read S2K octet.\n";
792 printf(STDERR "We cannot handle encrypted secret keys. Skipping!\n") ;
793 read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
797 # secret material is unencrypted
798 # see http://tools.ietf.org/html/rfc4880#section-5.5.3
799 my $d = read_mpi($instr, \$readbytes);
800 my $p = read_mpi($instr, \$readbytes);
801 my $q = read_mpi($instr, \$readbytes);
802 my $u = read_mpi($instr, \$readbytes);
805 read($instr, $checksum, 2) or die "Could not read checksum of secret key material.\n";
807 $checksum = unpack('n', $checksum);
809 # FIXME: compare with the checksum! how? the data is
810 # gone into the Crypt::OpenSSL::Bignum
812 $data->{key}->{rsa} = Crypt::OpenSSL::RSA->new_key_from_parameters($modulus,
818 $data->{key}->{rsa}->check_key() or die "Secret key is not a valid RSA key.\n";
820 if ($readbytes < $packetlen) {
821 read($instr, $dummy, $packetlen - $readbytes) or die "Could not skip past this packet.\n";
830 if (length($fpr) < 8) {
831 die "We need at least 8 hex digits of fingerprint.\n";
836 my $data = { target => { fpr => $fpr,
839 my $subs = { $packet_types->{pubkey} => \&findkey,
840 $packet_types->{pub_subkey} => \&findkey,
841 $packet_types->{seckey} => \&findkey,
842 $packet_types->{sec_subkey} => \&findkey };
844 packetwalk($instr, $subs, $data);
846 return $data->{key}->{rsa};
853 my $packetlen = shift;
855 findkey($data, $instr, $tag, $packetlen);
856 if (defined($data->{key})) {
857 if (defined($data->{key}->{rsa}) && defined($data->{key}->{timestamp})) {
858 $data->{keys}->{fingerprint($data->{key}->{rsa}, $data->{key}->{timestamp})} = $data->{key};
860 die "should have found some key here";
866 sub getallprimarykeys {
869 my $subs = { $packet_types->{pubkey} => \&findkeyfprs,
870 $packet_types->{seckey} => \&findkeyfprs,
872 my $data = {target => { } };
874 packetwalk($instr, $subs, $data);
876 if (defined $data->{keys}) {
877 return $data->{keys};
889 if ((! defined $fpr) ||
890 (length($fpr) < 8)) {
891 die "We need at least 8 hex digits of fingerprint.\n";
896 if (! defined $uid) {
897 die "No User ID defined.\n";
900 my $data = { target => { fpr => $fpr,
904 my $subs = { $packet_types->{seckey} => \&findkey,
905 $packet_types->{uid} => \&finduid,
906 $packet_types->{sig} => \&findsig,
909 packetwalk($instr, $subs, $data);
911 if ((! defined $data->{key}) ||
912 (! defined $data->{key}->{rsa}) ||
913 (! defined $data->{key}->{timestamp})) {
914 die "The key requested was not found.\n"
917 if (defined $data->{uid}->{$uid}) {
918 die "The requested User ID '$uid' is already associated with this key.\n";
920 $args->{key_timestamp} = $data->{key}->{timestamp};
923 make_packet($packet_types->{pubkey}, make_rsa_pub_key_body($data->{key}->{rsa}, $data->{key}->{timestamp})).
924 make_packet($packet_types->{uid}, $uid).
925 makeselfsig($data->{key}->{rsa},
938 if ((! defined $fpr) ||
939 (length($fpr) < 8)) {
940 die "We need at least 8 hex digits of fingerprint.\n";
945 if (! defined $uid) {
946 die "No User ID defined.\n";
949 my $data = { target => { fpr => $fpr,
953 my $subs = { $packet_types->{seckey} => \&findkey,
954 $packet_types->{uid} => \&finduid,
955 $packet_types->{sig} => \&findsig,
958 packetwalk($instr, $subs, $data);
960 if ((! defined $data->{uid}) ||
961 (! defined $data->{uid}->{$uid})) {
962 die "The User ID \"$uid\" is not associated with this key";
965 if ((! defined $data->{key}) ||
966 (! defined $data->{key}->{rsa}) ||
967 (! defined $data->{key}->{timestamp})) {
968 die "The key requested was not found."
971 my $revocation_reason = 'No longer using this hostname';
972 if (defined $data->{revocation_reason}) {
973 $revocation_reason = $data->{revocation_reason};
976 my $rev_reason_subpkt = prefixsubpacket(pack('CC',
977 $subpacket_types->{revocation_reason},
978 $revocation_reasons->{user_id_no_longer_valid}).
981 if (! defined $sigtime) {
984 # what does a signature like this look like?
985 my $args = { key_timestamp => $data->{key}->{timestamp},
986 sig_timestamp => $sigtime,
987 certification_type => $sig_types->{certification_revocation},
988 hashed_subpackets => $rev_reason_subpkt,
992 make_packet($packet_types->{pubkey}, make_rsa_pub_key_body($data->{key}->{rsa}, $data->{key}->{timestamp})).
993 make_packet($packet_types->{uid}, $uid).
994 join('', @{$data->{sigs}}).
995 gensig($data->{key}->{rsa}, $uid, $args);
999 # see 5.2.3.1 for tips on how to calculate the length of a subpacket:
1000 sub prefixsubpacket {
1001 my $subpacket = shift;
1003 my $len = length($subpacket);
1008 $prefix = pack('C', $len);
1009 } elsif ($len < 16576) {
1010 my $in = $len - 192;
1011 my $second = $in%256;
1012 my $first = ($in - $second)>>8;
1013 $prefix = pack('CC', $first + 192, $second)
1015 $prefix = pack('CN', 255, $len);
1017 return $prefix.$subpacket;
1031 while (! eof($instr)) {
1032 read($instr, $packettag, 1);
1033 $packettag = ord($packettag);
1036 if ( ! (0x80 & $packettag)) {
1037 die "This is not an OpenPGP packet\n";
1039 if (0x40 & $packettag) {
1040 # this is a new-format packet.
1041 $tag = (0x3f & $packettag);
1043 read($instr, $nextlen, 1);
1044 $nextlen = ord($nextlen);
1045 if ($nextlen < 192) {
1046 $packetlen = $nextlen;
1047 } elsif ($nextlen < 224) {
1049 read($instr, $newoct, 1);
1050 $newoct = ord($newoct);
1051 $packetlen = (($nextlen - 192) << 8) + ($newoct) + 192;
1052 } elsif ($nextlen == 255) {
1053 read($instr, $nextlen, 4);
1054 $packetlen = unpack('N', $nextlen);
1056 # packet length is undefined.
1059 # this is an old-format packet.
1061 $lentype = 0x03 & $packettag;
1062 $tag = ( 0x3c & $packettag ) >> 2;
1063 if ($lentype == 0) {
1064 read($instr, $packetlen, 1) or die "could not read packet length\n";
1065 $packetlen = unpack('C', $packetlen);
1066 } elsif ($lentype == 1) {
1067 read($instr, $packetlen, 2) or die "could not read packet length\n";
1068 $packetlen = unpack('n', $packetlen);
1069 } elsif ($lentype == 2) {
1070 read($instr, $packetlen, 4) or die "could not read packet length\n";
1071 $packetlen = unpack('N', $packetlen);
1073 # packet length is undefined.
1077 if (! defined($packetlen)) {
1078 die "Undefined packet lengths are not supported.\n";
1081 if (defined $subs->{$tag}) {
1082 $subs->{$tag}($data, $instr, $tag, $packetlen);
1084 read($instr, $dummy, $packetlen) or die "Could not skip past this packet!\n";
1088 return $data->{key};
1092 for (basename($0)) {
1093 if (/^pem2openpgp$/) {
1098 defined($uid) or die "You must specify a user ID string.\n";
1100 # FIXME: fail if there is no given user ID; or should we default to
1101 # hostname_long() from Sys::Hostname::Long ?
1103 if (defined $ENV{PEM2OPENPGP_NEWKEY}) {
1104 $rsa = Crypt::OpenSSL::RSA->generate_key($ENV{PEM2OPENPGP_NEWKEY});
1111 $rsa = Crypt::OpenSSL::RSA->new_private_key($stdin);
1114 my $key_timestamp = $ENV{PEM2OPENPGP_KEY_TIMESTAMP};
1115 my $sig_timestamp = $ENV{PEM2OPENPGP_TIMESTAMP};
1116 $sig_timestamp = time() if (!defined $sig_timestamp);
1117 $key_timestamp = $sig_timestamp if (!defined $key_timestamp);
1120 make_packet($packet_types->{seckey}, make_rsa_sec_key_body($rsa, $key_timestamp)).
1121 make_packet($packet_types->{uid}, $uid).
1124 { sig_timestamp => $sig_timestamp,
1125 key_timestamp => $key_timestamp,
1126 expiration => $ENV{PEM2OPENPGP_EXPIRATION},
1127 usage_flags => $ENV{PEM2OPENPGP_USAGE_FLAGS},
1131 elsif (/^openpgp2pem$/) {
1134 open($instream,'-');
1135 binmode($instream, ":bytes");
1136 my $key = openpgp2rsa($instream, $fpr);
1137 if (defined($key)) {
1138 if ($key->is_private()) {
1139 print $key->get_private_key_string();
1141 print $key->get_public_key_x509_string();
1144 die "No matching key found.\n";
1147 elsif (/^openpgp2ssh$/) {
1150 open($instream,'-');
1151 binmode($instream, ":bytes");
1152 my $key = openpgp2rsa($instream, $fpr);
1153 if (defined($key)) {
1154 if ($key->is_private()) {
1155 print $key->get_private_key_string();
1157 print "ssh-rsa ".encode_base64(openssh_pubkey_pack($key), '')."\n";
1160 die "No matching key found.\n";
1163 elsif (/^keytrans$/) {
1164 # subcommands when keytrans is invoked directly are UNSUPPORTED,
1165 # UNDOCUMENTED, and WILL NOT BE MAINTAINED.
1166 my $subcommand = shift;
1168 if (/^revokeuserid$/) {
1172 open($instream,'-');
1173 binmode($instream, ":bytes");
1175 my $revcert = revokeuserid($instream, $fpr, $uid, $ENV{PEM2OPENPGP_TIMESTAMP});
1178 } elsif (/^adduserid$/) {
1182 open($instream,'-');
1183 binmode($instream, ":bytes");
1184 my $newuid = adduserid($instream, $fpr, $uid,
1185 { sig_timestamp => $ENV{PEM2OPENPGP_TIMESTAMP},
1186 expiration => $ENV{PEM2OPENPGP_EXPIRATION},
1187 usage_flags => $ENV{PEM2OPENPGP_USAGE_FLAGS},
1191 } elsif (/^listfprs$/) {
1193 open($instream,'-');
1194 binmode($instream, ":bytes");
1195 my $keys = getallprimarykeys($instream);
1196 printf("%s\n", join("\n", map { uc(unpack('H*', $_)) } keys(%{$keys})));
1197 } elsif (/^sshfpr$/) {
1201 while (($dummy,$b64keyblob) = split(/ /, <STDIN>)) {
1202 printf("%s\n", sshfpr(decode_base64($b64keyblob)));
1204 } elsif (/^openpgp2sshfpr$/) {
1207 open($instream,'-');
1208 binmode($instream, ":bytes");
1209 my $key = openpgp2rsa($instream, $fpr);
1210 if (defined($key)) {
1211 # openssh uses MD5 for key fingerprints:
1212 printf("%d %s %s\n",
1213 $key->size() * 8, # size() is in bytes -- we want bits
1214 sshfpr(openssh_pubkey_pack($key)),
1215 '(RSA)', # FIXME when we support other than RSA.
1218 die "No matching key found.\n";
1221 die "Unrecognized subcommand. keytrans subcommands are not a stable interface!\n";
1226 die "Unrecognized keytrans call.\n";