File Coverage

lib/Crypt/RSA.pm
Criterion Covered Total %
statement 85 85 100.0
branch 13 26 50.0
condition 14 42 33.3
subroutine 16 16 100.0
pod 6 7 85.7
total 134 176 76.1


line stmt bran cond sub pod time code
1             #!/usr/bin/perl -sw
2             ##
3             ## Crypt::RSA - Pure-perl implementation of RSA encryption/signing
4             ## algorithms.
5             ##
6             ## Copyright (c) 2000-2001, Vipul Ved Prakash. All rights reserved.
7             ## This code is free software; you can redistribute it and/or modify
8             ## it under the same terms as Perl itself.
9             ##
10             ## $Id: RSA.pm,v 1.48 2001/09/25 12:44:55 vipul Exp $
11              
12             package Crypt::RSA;
13 11     11   157 use lib qw(lib);
  11         2671  
  11         157  
14 11     11   167 use strict;
  11         132  
  11         148  
15 11     11   153 use vars qw(@ISA $VERSION);
  11         96  
  11         176  
16 11     11   307 use Class::Loader;
  11         108  
  11         578  
17 11     11   245 use Crypt::RSA::Errorhandler;
  11         106  
  11         175  
18 11     11   270 use Crypt::RSA::Key;
  11         143  
  11         252  
19 11     11   175 use Crypt::RSA::DataFormat qw(steak octet_len);
  11         99  
  11         203  
20 11     11   399 use Convert::ASCII::Armour;
  11         133  
  11         275  
21 11     11   209 use Carp;
  11         104  
  11         221  
22              
23             @ISA = qw(Class::Loader Crypt::RSA::Errorhandler);
24             ($VERSION) = '$Revision: 1.58 $' =~ /\s(\d+\.\d+)\s/;
25              
26              
27             my %DEFAULTS = (
28                 'ES' => { Name => 'OAEP_ES' },
29                 'SS' => { Name => 'PSS_SS' },
30                 'PP' => { Name => 'ASCII_PP' },
31             );
32              
33              
34             my %KNOWNMAP = (
35              
36             # ENCRYPTION SCHEMES
37              
38                         OAEP_ES => { Module => "Crypt::RSA::ES::OAEP" },
39                     PKCS1v21_ES => { Module => "Crypt::RSA::ES::OAEP" },
40                     PKCS1v15_ES => { Module => "Crypt::RSA::ES::PKCS1v15" },
41              
42             # SIGNATURE SCHEMES
43              
44                          PSS_SS => { Module => "Crypt::RSA::SS::PSS" },
45                     PKCS1v21_SS => { Module => "Crypt::RSA::SS::PSS" },
46                     PKCS1v15_SS => { Module => "Crypt::RSA::SS::PKCS1v15" },
47              
48             # POST PROCESSORS
49              
50                        ASCII_PP => { Module => "Convert::ASCII::Armour" },
51              
52             );
53              
54              
55             sub new {
56              
57 1     1 1 11     my ($class, %params) = @_;
58 1         16     my %self = (%DEFAULTS, %params);
59 1         39     my $self = bless \%self, $class;
60              
61 1         26     $self->_storemap (%KNOWNMAP);
62                 
63 1         76     for (qw(ES SS PP)) {
64 3 50       77         $$self{$_} = { Name => $$self{$_} . "_$_" } unless ref $$self{$_};
65 3         28         $$self{lc($_)} = $self->_load ( %{$$self{$_}} );
  3         57  
66                 }
67              
68 1         89     $$self{keychain} = new Crypt::RSA::Key;
69              
70 1         43     return bless \%self, $class;
71              
72             }
73              
74              
75             sub keygen {
76              
77 3     3 1 51     my ($self, %params) = @_;
78 3 50       37     $params{KF} = $$self{KF} if $$self{KF};
79              
80 3         25     my @keys;
81 3 50       54     return (@keys = $self->{keychain}->generate (%params))
82                               ? @keys
83                               : $self->error ($self->{keychain}->errstr);
84              
85             } 
86              
87              
88             sub encrypt {
89              
90 3     3 1 2354     my ($self, %params) = @_;
91 3   33     122     my $plaintext = $params{Message} || $params{Plaintext};
92 3         508     my $key = $params{Key};
93              
94 3 50       369     return $self->error ($key->errstr, \%params, $key, \$plaintext)
95                     unless $key->check();
96              
97 3         106     my $blocksize = blocksize ( $$self{es}->encryptblock (Key => $key),
98                                             length($plaintext)
99                                           );
100              
101 3 50       64     return $self->error("Message too long.", \$key, \%params) if $blocksize <= 0;
102              
103 3         131     my $cyphertext;
104 3         37     my @segments = steak ($plaintext, $blocksize);
105 3         67     for (@segments) {
106 336   33     10066         $cyphertext .= $self->{es}->encrypt (Message => $_, Key => $key)
107                         || return $self->error ($self->{es}->errstr, \$key, \%params);
108                 }
109              
110 3 50 33     51     if ($params{Armour} || $params{Armor}) {
111 3         64         $cyphertext = $self->{pp}->armour (
112                          Object => 'RSA ENCRYPTED MESSAGE',
113                          Headers => {
114 3   33     51                 Scheme => $$self{ES}{Module} || ${$KNOWNMAP{$$self{ES}{Name}}}{Module},
115                             Version => $self->{es}->version()
116                          },
117                          Content => { Cyphertext => $cyphertext },
118                          Compress => 1,
119                     );
120                 }
121              
122 3         16489     return $cyphertext;
123              
124             }
125              
126              
127             sub decrypt {
128              
129 3     3 1 57     my ($self , %params) = @_;
130 3   33     96     my $cyphertext = $params{Cyphertext} || $params{Ciphertext};
131 3         27     my $key = $params{Key};
132              
133 3 50       49     return $self->error ($key->errstr, \%params, $key) unless $key->check();
134              
135 3 50 33     39     if ($params{Armour} || $params{Armor}) {
136 3   33     51         my $decoded = $self->{pp}->unarmour ($cyphertext) ||
137                         return $self->error ($self->{pp}->errstr());
138 3         5427         $cyphertext = $$decoded{Content}{Cyphertext}
139                 }
140              
141 3         32     my $plaintext;
142 3         93     my $blocksize = blocksize ( $$self{es}->decryptblock (Key => $key),
143                                             length($cyphertext)
144                                           );
145              
146 3 50       61     return $self->error("Message too long.") if $blocksize <= 0;
147              
148 3         39     my @segments = steak ($cyphertext, $blocksize);
149 3         69     for (@segments) {
150 336   33     6014         $plaintext .= $self->{es}->decrypt (Cyphertext=> $_, Key => $key)
151                         || return $self->error ($self->{es}->errstr, \$key, \%params);
152                 }
153              
154 3         1757     return $plaintext;
155              
156             }
157              
158              
159             sub sign {
160              
161 3     3 1 58     my ($self, %params) = @_;
162 3   33     111     my $signature = $self->{ss}->sign (%params)
163                              || return $self->error ($self->{ss}->errstr,
164                                     $params{Key}, \%params);
165              
166 3 50 33     49     if ($params{Armour} || $params{Armor}) {
167 3         63         $signature = $self->{pp}->armour (
168                            Object => "RSA SIGNATURE",
169                            Headers => {
170 3   33     50                     Scheme => $$self{SS}{Module} || ${$KNOWNMAP{$$self{SS}{Name}}}{Module},
171                                 Version => $self->{ss}->version() },
172                            Content => { Signature => $signature },
173                     );
174                 }
175              
176 3         824     return $signature;
177              
178             } 
179              
180              
181             sub verify {
182              
183 3     3 1 1253     my ($self, %params) = @_;
184              
185 3 50 33     43     if ($params{Armour} || $params{Armor}) {
186 3   33     48         my $decoded = $self->{pp}->unarmour ($params{Signature}) ||
187                         return $self->error ($self->{pp}->errstr());
188 3         766         $params{Signature} = $$decoded{Content}{Signature}
189                 }
190              
191 3   33     52     my $verify = $self->{ss}->verify (%params) ||
192                     return $self->error ($self->{ss}->errstr, $params{Key}, \%params);
193              
194 3         54     return $verify;
195              
196             }
197              
198              
199             sub blocksize {
200              
201 6     6 0 60     my ($blocksize, $ptsize) = @_;
202 6 50       125     return $ptsize if $blocksize == -1;
203 6 50       61     return 0 if $blocksize < 1;
204 6         422     return $blocksize;
205                     
206             }
207              
208             1; 
209              
210              
211             =head1 NAME
212            
213             Crypt::RSA - RSA public-key cryptosystem.
214            
215             =head1 VERSION
216            
217             $Revision: 1.48 $ (Beta)
218             $Date: 2001/09/25 12:44:55 $
219            
220             =head1 SYNOPSIS
221            
222             my $rsa = new Crypt::RSA;
223            
224             my ($public, $private) =
225             $rsa->keygen (
226             Identity => 'Lord Macbeth <macbeth@glamis.com>',
227             Size => 1024,
228             Password => 'A day so foul & fair',
229             Verbosity => 1,
230             ) or die $rsa->errstr();
231            
232            
233             my $cyphertext =
234             $rsa->encrypt (
235             Message => $message,
236             Key => $public,
237             Armour => 1,
238             ) || die $rsa->errstr();
239            
240            
241             my $plaintext =
242             $rsa->decrypt (
243             Cyphertext => $cyphertext,
244             Key => $private,
245             Armour => 1,
246             ) || die $rsa->errstr();
247            
248            
249             my $signature =
250             $rsa->sign (
251             Message => $message,
252             Key => $private
253             ) || die $rsa->errstr();
254            
255            
256             my $verify =
257             $rsa->verify (
258             Message => $message,
259             Signature => $signature,
260             Key => $public
261             ) || die $rsa->errstr();
262            
263             =head1 NOTE
264            
265             This manual assumes familiarity with public-key cryptography and the RSA
266             algorithm. If you don't know what these are or how they work, please refer
267             to the sci.crypt FAQ[15]. A formal treatment of RSA can be found in [1].
268            
269             =head1 DESCRIPTION
270            
271             Crypt::RSA is a pure-perl, cleanroom implementation of the RSA public-key
272             cryptosystem. It uses Math::Pari(3), a perl interface to the blazingly
273             fast PARI library, for big integer arithmetic and number theoretic
274             computations.
275            
276             Crypt::RSA provides arbitrary size key-pair generation, plaintext-aware
277             encryption (OAEP) and digital signatures with appendix (PSS). For
278             compatibility with SSLv3, RSAREF2, PGP and other applications that follow
279             the PKCS #1 v1.5 standard, it also provides PKCS #1 v1.5 encryption and
280             signatures.
281            
282             Crypt::RSA is structured as bundle of modules that encapsulate different
283             parts of the RSA cryptosystem. The RSA algorithm is implemented in
284             Crypt::RSA::Primitives(3). Encryption schemes, located under
285             Crypt::RSA::ES, and signature schemes, located under Crypt::RSA::SS, use
286             the RSA algorithm to build encryption/signature schemes that employ secure
287             padding. (See the note on Security of Padding Schemes.)
288            
289             The key generation engine and other functions that work on both components
290             of the key-pair are encapsulated in Crypt::RSA::Key(3).
291             Crypt::RSA::Key::Public(3) & Crypt::RSA::Key::Private(3) provide
292             mechanisms for storage & retrival of keys from disk, decoding & encoding
293             of keys in certain formats, and secure representation of keys in memory.
294             Finally, the Crypt::RSA module provides a convenient, DWIM wrapper around
295             the rest of the modules in the bundle.
296            
297             =head1 SECURITY OF PADDING SCHEMES
298            
299             It has been conclusively shown that textbook RSA is insecure[3,7]. Secure
300             RSA requires that plaintext is padded in a specific manner before
301             encryption and signing. There are four main standards for padding: PKCS
302             #1 v1.5 encryption & signatures, and OAEP encryption & PSS signatures.
303             Crypt::RSA implements these as four modules that
304             provide overloaded encrypt(), decrypt(), sign() and verify() methods that
305             add padding functionality to the basic RSA operations.
306            
307             Crypt::RSA::ES::PKCS1v15(3) implements PKCS #1 v1.5 encryption,
308             Crypt::RSA::SS::PKCS1v15(3) implements PKCS #1 v1.5 signatures,
309             Crypt::RSA::ES::OAEP(3) implements Optimal Asymmetric Encryption and
310             Crypt::RSA::SS::PSS(3) Probabilistic Signatures.
311            
312             PKCS #1 v1.5 schemes are older and hence more widely deployed, but PKCS #1
313             v1.5 encryption has certain flaws that make it vulnerable to
314             chosen-cyphertext attacks[9]. Even though Crypt::RSA works around these
315             vulnerabilities, it is recommended that new applications use OAEP and PSS,
316             both of which are provably secure[13]. In any event,
317             Crypt::RSA::Primitives (without padding) should never be used directly.
318            
319             That said, there exists a scheme called Simple RSA[16] that provides
320             security without padding. However, Crypt::RSA doesn't implement this
321             scheme yet.
322            
323             =head1 METHODS
324            
325             =over 4
326            
327             =item B<new()>
328            
329             The constructor. When no arguments are provided, new() returns an object
330             loaded with default values. This object can be customized by specifying
331             encryption & signature schemes, key formats and post processors. For
332             details see the section on B<Customizing the Crypt::RSA
333             object> later in this manpage.
334            
335             =item B<keygen()>
336            
337             keygen() generates and returns an RSA key-pair of specified bitsize.
338             keygen() is a synonym for Crypt::RSA::Key::generate(). Parameters and
339             return values are described in the Crypt::RSA::Key(3) manpage.
340            
341             =item B<encrypt()>
342            
343             encrypt() performs RSA encryption on a string of arbitrary length with a
344             public key using the encryption scheme bound to the object. The default
345             scheme is OAEP. encrypt() returns cyphertext (a string) on success and
346             undef on failure. It takes a hash as argument with following keys:
347            
348             =over 4
349            
350             =item B<Message>
351            
352             An arbitrary length string to be encrypted.
353            
354             =item B<Key>
355            
356             Public key of the recipient, a Crypt::RSA::Key::Public(3) or
357             compatible object.
358            
359             =item B<Armour>
360            
361             A boolean parameter that forces cyphertext through a post processor after
362             encrpytion. The default post processor is Convert::ASCII::Armour(3) that
363             encodes binary octets in 6-bit clean ASCII messages. The cyphertext is
364             returned as-is, when the Armour key is not present.
365            
366             =back
367            
368             =item B<decrypt()>
369            
370             decrypt() performs RSA decryption with a private key using the encryption
371             scheme bound to the object. The default scheme is OAEP. decrypt() returns
372             plaintext on success and undef on failure. It takes a hash as argument
373             with following keys:
374            
375             =over 4
376            
377             =item B<Cyphertext>
378            
379             Cyphertext of arbitrary length.
380            
381             =item B<Key>
382            
383             Private key, a Crypt::RSA::Key::Private(3) or compatible object.
384            
385             =item B<Armour>
386            
387             Boolean parameter that specifies whether the Cyphertext is encoded with a
388             post processor.
389            
390             =back
391            
392             =item B<sign()>
393            
394             sign() creates an RSA signature on a string with a private key using the
395             signature scheme bound to the object. The default scheme is
396             PSS. sign() returns a signature on success and undef on failure. It takes
397             a hash as argument with following keys:
398            
399             =over 4
400            
401             =item B<Message>
402            
403             A string of arbitrary length to be signed.
404            
405             =item B<Key>
406            
407             Private key of the sender, a Crypt::RSA::Key::Private(3) or
408             compatible object.
409            
410             =item B<Armour>
411            
412             A boolean parameter that forces the computed signature to be post
413             processed.
414            
415             =back
416            
417             =item B<verify()>
418            
419             verify() verifies an RSA signature with a public key using the signature
420             scheme bound to the object. The default scheme is PSS. verify() returns a
421             true value on success and undef on failure. It takes a hash as argument
422             with following keys:
423            
424             =over 4
425            
426             =item B<Message>
427            
428             A signed message, a string of arbitrary length.
429            
430             =item B<Key>
431            
432             Public key of the signer, a Crypt::RSA::Key::Public(3) or
433             compatible object.
434            
435             =item B<Sign>
436            
437             A signature computed with sign().
438            
439             =item B<Armour>
440            
441             Boolean parameter that specifies whether the Signature has been
442             post processed.
443            
444             =back
445            
446             =back
447            
448             =head1 MODULES
449            
450             Apart from Crypt::RSA, the following modules are intended for application
451             developer and end-user consumption:
452            
453             =over 4
454            
455             =item B<Crypt::RSA::Key>
456            
457             RSA key pair generator.
458            
459             =item B<Crypt::RSA::Key::Public>
460            
461             RSA Public Key Management.
462            
463             =item B<Crypt::RSA::Key::Private>
464            
465             RSA Private Key Management.
466            
467             =item B<Crypt::RSA::ES::OAEP>
468            
469             Plaintext-aware encryption with RSA.
470            
471             =item B<Crypt::RSA::SS::PSS>
472            
473             Probabilistic Signature Scheme based on RSA.
474            
475             =item B<Crypt::RSA::ES::PKCS1v15>
476            
477             PKCS #1 v1.5 encryption scheme.
478            
479             =item B<Crypt::RSA::SS::PKCS1v15>
480            
481             PKCS #1 v1.5 signature scheme.
482            
483             =back
484            
485             =head1 CUSTOMISING A CRYPT::RSA OBJECT
486            
487             A Crypt::RSA object can be customized by passing any of the following keys
488             in a hash to new(): ES to specify the encryption scheme, SS to specify the
489             signature scheme, PP to specify the post processor, and KF to specify the
490             key format. The value associated with these keys can either be a name (a
491             string) or a hash reference that specifies a module name, its constructor,
492             and constructor arguments. For example:
493            
494             my $rsa = new Crypt::RSA ( ES => 'OAEP' );
495            
496             or
497            
498             my $rsa = new Crypt::RSA ( ES => { Module => 'Crypt::RSA::ES::OAEP' } );
499            
500             A module thus specified need not be included in the Crypt::RSA bundle, but
501             it must be interface compatible with the ones provided with Crypt::RSA.
502            
503             As of this writing, the following names are recognised:
504            
505             =over 4
506            
507             =item B<ES> (Encryption Scheme)
508            
509             'OAEP', 'PKCS1v15'
510            
511             =item B<SS> (Signature Scheme)
512            
513             'PSS', 'PKCS1v15'
514            
515             =item B<KF> (Key Format)
516            
517             'Native', 'SSH'
518            
519             =item B<PP> (Post Processor)
520            
521             'ASCII'
522            
523             =back
524            
525             =head1 ERROR HANDLING
526            
527             All modules in the Crypt::RSA bundle use a common error handling method
528             (implemented in Crypt::RSA::Errorhandler(3)). When a method fails it
529             returns undef and calls $self->error() with the error message. This error
530             message is available to the caller through the errstr() method. For more
531             details see the Crypt::RSA::Errorhandler(3) manpage.
532            
533             =head1 AUTHOR
534            
535             Vipul Ved Prakash, E<lt>mail@vipul.netE<gt>
536            
537             =head1 ACKNOWLEDGEMENTS
538            
539             Thanks to Ilya Zakharevich for help with Math::Pari, Benjamin Trott for
540             several patches including SSH key support, Genèche Ramanoudjame for
541             extensive testing and numerous bug reports, Shizukesa on #perl for
542             suggesting the error handling method used in this module, and Dave Paris
543             for good advice.
544            
545             =head1 LICENSE
546            
547             Copyright (c) 2000-2005, Vipul Ved Prakash. All rights reserved.
548             This code is free software; it is distributed under a
549             disjunctive Artistic/GPL license, like Perl itself.
550            
551             I have received requests for commercial licenses of
552             Crypt::RSA, from those who desire contractual support and
553             indemnification. I'd be happy to provide a commercial license
554             if you need one. Please send me mail at C<mail@vipul.net> with
555             the subject "Crypt::RSA license". Please don't send me mail
556             asking if you need a commercial license. You don't, if
557             Artistic of GPL suit you fine.
558            
559             =head1 SEE ALSO
560            
561             Crypt::RSA::Primitives(3), Crypt::RSA::DataFormat(3),
562             Crypt::RSA::Errorhandler(3), Crypt::RSA::Debug(3), Crypt::Primes(3),
563             Crypt::Random(3), Crypt::CBC(3), Crypt::Blowfish(3),
564             Tie::EncryptedHash(3), Convert::ASCII::Armour(3), Math::Pari(3),
565             Class::Loader(3), crypt-rsa-interoperability(3),
566             crypt-rsa-interoperability-table(3).
567            
568             =head1 REPORTING BUGS
569            
570             All bug reports related to Crypt::RSA should go to rt.cpan.org
571             at C<http://rt.cpan.org/Dist/Display.html?Queue=Crypt-RSA>
572            
573             Crypt::RSA is considered to be stable. If you are running into a
574             problem, it's likely of your own making. Please check your code
575             and consult the documentation before posting a bug report. A
576             google search with the error message might also shed light if it
577             is a common mistake that you've made.
578            
579             If the module installation fails with a "Segmentation Fault" or
580             "Bus Error", it is likely a Math::Pari issue. Please consult
581             Math::Pari bugs on rt.cpan.org or open a bug there. There have
582             been known issues on HP-UX and SunOS systems (with Math::Pari),
583             so if you are on those OSes, please consult Math::Pari
584             resources before opening a Crypt::RSA bug.
585            
586             =head1 BIBLIOGRAPHY
587            
588             Chronologically sorted (for the most part).
589            
590             =over 4
591            
592             =item 1 B<R. Rivest, A. Shamir, L. Aldeman.> A Method for Obtaining Digital Signatures and Public-Key Cryptosystems (1978).
593            
594             =item 2 B<U. Maurer.> Fast Generation of Prime Numbers and Secure Public-Key Cryptographic Parameters (1994).
595            
596             =item 3 B<M. Bellare, P. Rogaway.> Optimal Asymmetric Encryption - How to Encrypt with RSA (1995).
597            
598             =item 4 B<M. Bellare, P. Rogaway.> The Exact Security of Digital Signatures - How to sign with RSA and Rabin (1996).
599            
600             =item 5 B<B. Schneier.> Applied Cryptography, Second Edition (1996).
601            
602             =item 6 B<A. Menezes, P. Oorschot, S. Vanstone.> Handbook of Applied Cryptography (1997).
603            
604             =item 7 B<D. Boneh.> Twenty Years of Attacks on the RSA Cryptosystem (1998).
605            
606             =item 8 B<D. Bleichenbacher, M. Joye, J. Quisquater.> A New and Optimal Chosen-message Attack on RSA-type Cryptosystems (1998).
607            
608             =item 9 B<B. Kaliski, J. Staddon.> Recent Results on PKCS #1: RSA Encryption Standard, RSA Labs Bulletin Number 7 (1998).
609            
610             =item 10 B<B. Kaliski, J. Staddon.> PKCS #1: RSA Cryptography Specifications v2.0, RFC 2437 (1998).
611            
612             =item 11 B<SSH Communications Security.> SSH 1.2.7 source code (1998).
613            
614             =item 12 B<S. Simpson.> PGP DH vs. RSA FAQ v1.5 (1999).
615            
616             =item 13 B<RSA Laboratories.> Draft I, PKCS #1 v2.1: RSA Cryptography Standard (1999).
617            
618             =item 14 B<E. Young, T. Hudson, OpenSSL Team.> OpenSSL 0.9.5a source code (2000).
619            
620             =item 15 B<Several Authors.> The sci.crypt FAQ at
621             http://www.faqs.org/faqs/cryptography-faq/part01/index.html
622            
623             =item 16 B<Victor Shoup.> A Proposal for an ISO Standard for Public Key Encryption (2001).
624            
625             =cut
626              
627              
628