SSH2.pm

filter: Statementstmt 89.3% 84 / 94 Branchbran 50.0% 12 / 24 Conditioncond 33.3% 1 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 89.4% 17 / 19 Podpod 75.0% 3 / 4 totaltotal 80.1% 117 / 146 CC 14 SCAR 16.3
CC
14
Cov
80%
write
20.0
parse
7.4
BUILD
3.0
CRAP 5.1
↑ Summary SSH2/Format/PKCS8.pm »
1 package Convert::SSH2;
2  
3 3 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 3 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 3 ▶use MIME::Base64 qw(decode_base64);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 3 ▶use File::Slurp qw(read_file write_file);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 3 ▶use Carp qw(confess);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 3 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 3 ▶use Class::Load qw(load_class);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 3 ▶use Math::BigInt try => 'GMP';
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 =head1 NAME
16  
17 Convert::SSH2 - Convert SSH2 RSA keys to other formats
18  
19 =head1 VERSION
20  
21 Version 0.01
22  
23 =cut
24  
25 3 our $VERSION = '0.01';
26  
27 =head1 SYNOPSIS
28  
29 use 5.010;
30 use Convert::SSH2;
31  
32 my $converter = Convert::SSH2->new('~/.ssh/id_rsa.pub');
33 # Automatically calls parse()
34  
35 # Use default PKCS#1 format
36 say $converter->format_output();
37  
38 $converter->write('/my/pub/key.pem');
39  
40  
41 =head1 PURPOSE
42  
43 This library converts SSH2 style RSA public keys to other representations like PKCS#1.
44 This is useful if you want to use these public keys with other Perl cryptography
45 libraries like L<Crypt::RSA> or L<Crypt::OpenSSL::RSA>.
46  
47 =head1 ATTRIBUTES
48  
49 =over
50  
51 =item key
52  
53 Required. Read-only. The key material. Attempts to be DWIMish. If this is a file path,
54 it will be used to load the file contents into memory. If it's a buffer, it will use
55 the buffer contents.
56  
57 =back
58  
59 =cut
60  
61 3 has 'key' => (
62 is => 'ro',
63 required => 1,
64 );
65  
66 =over
67  
68 =item format
69  
70 Read-only. The output format. Current supports:
71  
72 =over
73  
74 =item * pkcs1
75  
76 This format looks like
77  
78 -----BEGIN RSA PUBLIC KEY-----
79 ...
80 -----END RSA PUBLIC KEY-----
81  
82 =item * pkcs8
83  
84 This format looks like
85  
86 -----BEGIN PUBLIC KEY-----
87 ...
88 -----END PUBLIC KEY-----
89  
90 =back
91  
92 You can add your own format by implementing a L<Convert::SSH2::Format::Base> module.
93  
94 =back
95  
96 =cut
97  
98 has 'format' => (
99 is => 'ro',
100 4 ▶ isa => sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
101 4 my $n = shift;
102 confess "$n is not a supported format." unless
103 4 ▶ grep { $n eq $_ } qw(
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$n eq $_;} "pkcs1", "pkcs8" 0 4 4
104 pkcs1
105 pkcs8
106 );
107 },
108 2 ▶ default => sub { 'pkcs1' },
Subroutine __ANON__: called CC=1 SCAR=0.0
109 3 );
110  
111 3 has '_buffer' => (
112 is => 'rw',
113 );
114  
115 3 has '_output' => (
116 is => 'rw',
117 predicate => '_has_output',
118 );
119  
120 3 has '_e' => (
121 is => 'rw',
122 );
123  
124 3 has '_n' => (
125 is => 'rw',
126 );
127  
128 =head1 METHODS
129  
130 Generally, errors are fatal. Use L<Try::Tiny> if you want more graceful error handling.
131  
132 =over
133  
134 =item new()
135  
136 Constructor. Takes any of the attributes as arguments. You may optionally call new
137 with either a buffer or a path, and the class will assume that it is the C<key>
138 material.
139  
140 The object automatically attempts to parse C<key> data after instantiation.
141  
142 =back
143  
144 =cut
145  
146 # Support single caller argument
147 4 ▶around BUILDARGS => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
148 4 my $orig = shift;
149 4 my $class = shift;
150  
151 4 ▶ if ( @_ == 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 1) 2 2 4
152 2 unshift @_, "key";
153 }
154  
155 4 $class->$orig(@_);
156 3 };
157  
158 4 ▶sub BUILD {
Subroutine BUILD: called CC=3 SCAR=11.1
Pod undocumented
159 4 my $self = shift;
160  
161 4 my $buf;
162 4 ▶ unless ( $self->key =~ /\n/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->key =~ /\n/) { } 2 2 4
163 2 ▶ if ( -e $self->key ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-e $self->key) { } 2 0 2
164 2 $buf = read_file($self->key, { binmode => ':raw' });
165 }
166 else {
167 0 $buf = $self->key;
168 }
169 }
170 else {
171 2 $buf = $self->key;
172 }
173  
174 4 $buf =~ s/\n//g;
175 4 $self->_buffer( (split / /, $buf)[1] );
176  
177 4 $self->parse();
178 }
179  
180 =over
181  
182 =item parse()
183  
184 This method takes the Base64 encoded portion of the SSH key, decodes it, and then converts the
185 data inside of it into three components: the id string ('ssh-rsa'), the public exponent ('e'),
186 and the modulus ('n'). By default it looks for the Base64 data inside the instantiated object,
187 but you can optionally pass in a Base64 string.
188  
189 It uses L<Math::BigInt> to hold large integers such as 'n' or 'e'. If you don't have
190 C<libgmp> installed, it will fall back to pure perl automatically, but there will be a speed
191 penalty.
192  
193 Returns a true value on success.
194  
195 =back
196  
197 =cut
198  
199 4 ▶sub parse {
Subroutine parse: called CC=7 SCAR=20.1
Pod documented
200 4 my $self = shift;
201 4 ▶ my $b64 = shift || $self->_buffer;
Condition33%1/3
shift() || $self->_buffer
l!l&&r!l&&!r
040
MC/DC0%0/2
shift() || $self->_buffer
shift() $self->_buffer
Truth table33%1/3
A || B
A= shift()B= $self->_buffer
ABresult
1X1
011
000
202  
203 4 ▶ confess "I don't have a buffer!" unless $b64;
Branch: 1 branch
BranchTrueFalseTotal
unless $b64 0 4 4
204  
205 4 ▶ my $blob = decode_base64($b64) or confess "Couldn't Base64 decode buffer";
Branch: 1 branch
BranchTrueFalseTotal
my $blob = &decode_base64($b64) or confess("Couldn't Base64 decode buffer") 4 0 4
206  
207 4 my @parts;
208 4 my $len = length($blob);
209 4 my $pos = 0;
210  
211 4 ▶ while ( $pos < $len ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < $len) 12 4 16
212 # There's probably a clever way to do this, but this works ok.
213 12 my $dlen = hex( unpack "H*", substr($blob, $pos, 4) );
214 12 $pos += 4;
215 12 push @parts, substr($blob, $pos, $dlen);
216 12 $pos += $dlen;
217 }
218  
219 # ok $parts[0] should be a string, $parts[1] the exponent 'e', and $parts[2] the modulus 'n'
220  
221 4 ▶ confess "Invalid key type" unless unpack "A*", $parts[0] eq 'ssh-rsa';
Branch: 1 branch
BranchTrueFalseTotal
unless unpack "A*", $parts[0] eq "ssh-rsa" 0 4 4
222  
223 4 my $e;
224 4 ▶ if ( length($parts[1]) <= 4 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $parts[1] <= 4) { } 4 0 4
225 4 $e = hex( unpack "H*", $parts[1] );
226 }
227 else {
228 0 $e = Math::BigInt->new( ("0x" . unpack "H*", $parts[1]) );
229 }
230  
231 4 my $n = Math::BigInt->new( ("0x" . unpack "H*", $parts[2]) );
232  
233 4 $self->_e( $e );
234 4 $self->_n( $n );
235  
236 4 return 1;
237 }
238  
239 =over
240  
241 =item format_output()
242  
243 Using a subclass of L<Convert::SSH2::Format::Base>, generate a representation of the SSH2 key.
244  
245 Returns a formatted string.
246  
247 =back
248  
249 =cut
250  
251 4 ▶sub format_output {
Subroutine format_output: called CC=1 SCAR=0.0
Pod documented
252 4 my $self = shift;
253 4 my $format = "Convert::SSH2::Format::" . uc($self->format);
254  
255 4 ▶ try {
Subroutine __ANON__: called CC=1 SCAR=0.0
256 4 load_class $format;
257 }
258 0 ▶ catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
259 0 confess "Couldn't load formatter $format: $_";
260 4 };
261  
262 4 my $fmt = $format->new(
263 e => $self->_e,
264 n => $self->_n,
265 );
266  
267 4 my $str = $fmt->generate();
268  
269 4 $self->_output( $str );
270  
271 4 return $str;
272 }
273  
274 =over
275  
276 =item write()
277  
278 Convenience method to write a formatted key representation to a file.
279  
280 Expects a pathname. Automatically calls C<format_output()> if necessary.
281 If the output format has been generated already, it uses a cached version.
282  
283 Returns a true value on success.
284  
285 =back
286  
287 =cut
288  
289 0 ▶sub write {
Subroutine write: not called CC=4 SCAR=30.0
Pod documented
290 0 my $self = shift;
291 0 my $path = shift;
292  
293 0 ▶ confess "I don't have a path" unless $path;
Branch: 1 branch
BranchTrueFalseTotal
unless $path 0 0 0
294  
295 0 ▶ if ( -e $path ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-e $path) 0 0 0
296 0 confess "$path seems to exist already?";
297 }
298  
299 0 ▶ $self->format_output() unless $self->_has_output;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_has_output 0 0 0
300  
301 0 write_file( $path, { noclobber => 1, binmode => ":raw" }, $self->_output );
302 }
303  
304 =head1 AUTHOR
305  
306 Mark Allen, C<< <mrallen1 at yahoo.com> >>
307  
308 =head1 BUGS
309  
310 Please report any bugs or feature requests to C<bug-convert-ssh2 at rt.cpan.org>, or through
311 the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Convert-SSH2>. I will be notified, and then you'll
312 automatically be notified of progress on your bug as I make changes.
313  
314 =head1 SUPPORT
315  
316 You can find documentation for this module with the perldoc command.
317  
318 perldoc Convert::SSH2
319  
320 You can also look for information at:
321  
322 =over 4
323  
324 =item * RT: CPAN's request tracker (report bugs here)
325  
326 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Convert-SSH2>
327  
328 =item * AnnoCPAN: Annotated CPAN documentation
329  
330 L<http://annocpan.org/dist/Convert-SSH2>
331  
332 =item * CPAN Ratings
333  
334 L<http://cpanratings.perl.org/d/Convert-SSH2>
335  
336 =item * MetaCPAN
337  
338 L<https://metacpan.org/dist/Convert-SSH2>
339  
340 =item * Git Hub
341  
342 L<https://github.com/mrallen1/Convert-SSH2>
343  
344 =back
345  
346 =head1 SEE ALSO
347  
348 L<Convert::SSH2::Format::Base>, L<Convert::SSH2::Format::PKCS1>
349  
350 L<Converting OpenSSH public keys|http://blog.oddbit.com/2011/05/converting-openssh-public-keys.html>
351  
352 =head1 ACKNOWLEDGEMENTS
353  
354 Mark Cavage
355  
356 =head1 LICENSE AND COPYRIGHT
357  
358 Copyright 2012 Mark Allen.
359  
360 This program is free software; you can redistribute it and/or modify it
361 under the terms of either: the GNU General Public License as published
362 by the Free Software Foundation; or the Artistic License.
363  
364 See http://dev.perl.org/licenses/ for more information.
365  
366 =cut
367  
368 3 1; # End of Convert::SSH2
↑ Summary SSH2/Format/PKCS8.pm »