File Coverage

lib/Crypt/RSA.pm
Criterion Covered Total %
statement 12 12 100.0
branch n/a
condition n/a
subroutine 4 4 100.0
pod n/a
total 16 16 100.0


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