home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / egd.pm < prev    next >
Encoding:
Perl POD Document  |  2001-07-12  |  2.0 KB  |  91 lines

  1. #!/usr/bin/perl -sw
  2. ##
  3. ##
  4. ##
  5. ## Copyright (c) 2001, Vipul Ved Prakash.  All rights reserved.
  6. ## This code is free software; you can redistribute it and/or modify
  7. ## it under the same terms as Perl itself.
  8. ##
  9. ## $Id: egd.pm,v 1.5 2001/07/12 15:59:48 vipul Exp $
  10.  
  11. package Crypt::Random::Provider::egd;
  12. use strict;
  13.  
  14. use IO::Socket;
  15. use Carp;
  16. use Math::Pari qw(pari2num);
  17.  
  18.  
  19. sub _defaultsource { 
  20.  
  21.     my $source;
  22.     for my $d (qw( /var/run/egd-pool /dev/egd-pool /etc/entropy )) {
  23.         if (IO::Socket::UNIX->new(Peer => $d)) { $source = $d; last }
  24.     }
  25.     return $source;
  26.  
  27. }
  28.  
  29.  
  30. sub new { 
  31.  
  32.     my ($class, %args) = @_;
  33.     my $self = { Source => $args{Source} || $args{Device} || $args{Filename} };
  34.     $$self{Source} = $class->_defaultsource() unless $$self{Source};
  35.     croak "egd entropy pool file not found.\n" unless $$self{Source};
  36.     return bless $self, $class;
  37.  
  38. }
  39.  
  40.  
  41. sub get_data {
  42.    
  43.     my ( $self, %params ) = @_;
  44.     my $class = ref $self || $self;
  45.     $self = {} unless ref $self;
  46.  
  47.     my $bytes    = $params{Length} ||
  48.                    (int( pari2num($params{ Size }) / 8) + 1);
  49.     my $dev      = $params{Source} || $$self{Source};
  50.     my $skip     = $params{Skip};
  51.  
  52.     croak "$dev doesn't exist.  aborting." unless $dev && -e $dev;
  53.  
  54.     my $s = IO::Socket::UNIX->new(Peer => $dev);
  55.     croak "couldn't talk to egd. $!" unless $s;
  56.  
  57.     my($r, $read) = ('', 0);
  58.     while ($read < $bytes) {
  59.         my $msg = pack "CC", 0x01, 1;
  60.         $s->syswrite($msg, length $msg);
  61.         my $rt;
  62.         my $nread = $s->sysread($rt, 1);
  63.         croak "read from entropy socket failed" unless $nread == 1;
  64.         my $count = unpack("C", $rt);
  65.         $nread = $s->sysread($rt, $count);
  66.         croak "couldn't get all the requested entropy.  aborting."
  67.             unless $nread == $count;
  68.         unless ($skip && $skip =~ /\Q$rt\E/) {
  69.             if ($params{Verbosity}) { print '.' unless $read % 2 }
  70.             $r .= $rt;
  71.             $read++;
  72.         }
  73.     }
  74.  
  75.     $r;
  76. }
  77.  
  78.  
  79. sub available { 
  80.    
  81.     my $class = shift; 
  82.     return 1 if $class->_defaultsource();
  83.     return;
  84.  
  85. }
  86.  
  87.  
  88. 1;
  89.  
  90.  
  91.