d89d2a55dda93764bbcbdfcd6b1595fb2f332619
[monkeysphere-validation-agent.git] / Crypt / Monkeysphere / Keytrans.pm
1 package Crypt::Monkeysphere::Keytrans;
2
3 use strict;
4 use warnings;
5 use Math::BigInt;
6
7 use Exporter qw(import);
8 our @EXPORT_OK=qw(openssh_rsa_pubkey_pack);
9
10
11 # takes a Math::BigInt and returns it properly packed for openssh output.
12
13 sub openssh_mpi_pack {
14   my $num = shift;
15
16   my $val = $num->as_hex();
17   $val =~ s/^0x//;
18   # ensure we've got an even multiple of 2 nybbles here.
19   $val = '0'.$val
20     if (length($val) % 2);
21   $val = pack('H*', $val);
22   # packed binary ones-complement representation of the value.
23
24   my $mpilen = length($val);
25
26   my $ret = pack('N', $mpilen);
27
28   # if the first bit of the leading byte is high, we should include a
29   # 0 byte:
30   if (ord($val) & 0x80) {
31     $ret = pack('NC', $mpilen+1, 0);
32   }
33
34   return $ret.$val;
35 }
36
37 # this output is not base64-encoded yet.  Pass it through
38 # encode_base64($output, '') if you want to make a file.
39
40 sub openssh_rsa_pubkey_pack {
41   my ($modulus, $exponent) = @_;
42
43   return openssh_mpi_pack(Math::BigInt->new('0x'.unpack('H*', "ssh-rsa"))).
44       openssh_mpi_pack($exponent).
45         openssh_mpi_pack($modulus);
46 }
47
48
49 1;