www.farid-hajji.net banner

Farid Hajji

Perl: Einführung, Anwendungen, Referenz (2/e) [Support-Site]

Farid Hajji: Perl - Einführung, Anwendungen, Referenz
2., aktualisierte und erweiterte Auflage
Addison-Wesley Longman, ISBN 3-8273-1535-2

Beispielprogramm

cgi-s-cookie-md5.pl
#!/usr/local/bin/perl -w
# cgi-s-cookie-md5.pl -- Zustandserhaltung mit Cookies, MD5-Signatur.

use strict;
use CGI qw(:standard);
use CGI::Carp qw(fatalsToBrowser);
use CGI::Cookie;
use Digest::MD5 qw(md5_hex);

my $state = retrieve_state();
compute_next_state($state);
my $newcookie  = save_state($state);

# Tue etwas abhaengig von $state:
print header(-cookie => $newcookie),
    start_html('State with Cookies'),
    "Current state: ", $state->{'INFO'}, p,
    "If you call me again, I'll increment it for you",
    end_html;

use constant INITSTATE => 1;
use constant STATENAME => 'mystatemd5';
use constant STATETTL  => '+5m';
use constant SECRET    => 'wefoij238ghooic2';
sub generate_MAC {
    my $content = shift;
    return md5_hex(SECRET . md5_hex(SECRET . $content));
}

sub check_MAC {
    my $state = shift;

    die "State content has been tempered with!"
    unless generate_MAC($state->{'INFO'}) eq $state->{'MAC'};
}

sub retrieve_state {
    my %state = cookie(-name => STATENAME);
    %state    =  ( INFO => INITSTATE,
           MAC  => generate_MAC(INITSTATE) )
    unless exists $state{'INFO'} and exists $state{'MAC'};

    check_MAC(\%state);

    return \%state;
}

sub compute_next_state {
    my $state = shift;
    $state->{'INFO'} = $state->{'INFO'} + 1;
    $state->{'MAC'}  = generate_MAC($state->{'INFO'});
}

sub save_state {
    my $state  = shift;
    my $cookie = new CGI::Cookie(-name     => STATENAME,
                 -value    => $state,
                     -expires  => STATETTL);
    return $cookie;
}
   

[Prev] [Up] [Relevant Chapter] [Next]

[Alte Quelle]


Last modified: $Date: 2006/05/18 12:55:53 $
FH. Search :: Sitemap :: Disclaimer :: Copyright :: Privacy
FreeBSD Logo