Activator

 view release on metacpan or  search on metacpan

lib/Catalyst/Plugin/SecureCookies.pm  view on Meta::CPAN

Description:
  Takes a hashref representing web form elements, encrypts the components, creates a base64 safe url string

Args:
  $form_hasref - hashref of vars

Return:
  $encoded     - the encoded form
  $csum        - the checksum

=cut

sub _encrypt {
    my ( $c, $form_hashref ) = @_;

    my $cipher = &_get_cipher( $c->config->{SecureCookies}->{key} );

    ## first url encode it
    my $encoded = &_url_encode_hashref( $form_hashref );

    ## now we encrypt and mime encode it
    my $encrypted = $cipher->encrypt( $encoded );
#    $encrypted =~ s/^RandomIV//;
    my $mimed = &_base64_encode_url( $encrypted );

    ## checksum it
    my $ctx = new Digest::SHA1;
    $ctx->add( $mimed );
    my $csum = substr( &_base64_encode_url( $ctx->digest ), 3, 4 );

    ## give em what they want
    return ($mimed, $csum);
}

=item B<_decrypt>

Description:
  Takes a base64 safe url string representing form elements, decrypts the components, creates a hashref
m
Args:
  $encoded      - encoded form
  $csum         - csum for the form

Return:
  $form_hashref - hashref of the variables

=cut

sub _decrypt {
    my ( $c, $encoded, $csum ) = @_;

    my $cipher = &_get_cipher( $c->config->{SecureCookies}->{key} );

    ## calc a csum for the encrypted block
    my $ctx = new Digest::SHA1;
    $ctx->add( $encoded );

    my $this_csum = substr( &_base64_encode_url( $ctx->digest ), 3, 4 );

    ## compare it
    if( $csum ne $this_csum ) { return undef; }

    ## ok, the csum is good, decrypt
    my $encrypted = &_base64_decode_url( $encoded );
#    $encrypted = "RandomIV".$encrypted;
    my $dec = $cipher->decrypt( $encrypted );

    ## get the form
    my $form_hashref = &_url_decode_hashref( $dec );

    return $form_hashref;

}

=item B<_base64_encode_url>

Description:
 - safely encode using base64 to be used in urls

=cut

sub _base64_encode_url {
    my ($data, $separator) = @_;

    my $mimed = encode_base64( $data, $separator );

    ## convert to web friendlies
    $mimed =~ s/\s//g;
    $mimed =~ tr/[\+\/\=]/[\_\-.]/;
    return $mimed;
}

=item B<_base64_decode_url>

Description:
 - safely decode base64 from urls

=cut

sub _base64_decode_url {
    my ($mimed) = @_;

    ## convert from web friendlies
    $mimed =~ tr/[\_\-.]/[\+\/\=]/;

    return decode_base64( $mimed );
}

sub _get_cipher {
    my $key = shift;
    if ( !$CIPHER ) {
	$CIPHER = new Crypt::CBC( -key => pack("H16", $key), 
				  -cipher => 'Blowfish' );
    }
    return $CIPHER;
}

sub _url_encode_hashref {
    my ($form_hashref) = @_;

    ## bail if it's not a form



( run in 1.238 second using v1.01-cache-2.11-cpan-d80b1682f3f )