qodeninja
qodeninja

Reputation: 11286

How do you URL Base64 Encode and Decode a concatenated string in Perl?

I have a function that stringifies timeout information that I want to base64 url encode , but when I try to decode the encoded string, it gives back junk that looks nothing like the string originally created.

Output

   [i] original string > 05cee990c62ca2ce5dfe6cd77115a96d|1331012040|1331004840|7200
   [i] encoded string > MDVjZWU5OTBjNjJjYTJjZTVkZmU2Y2Q3NzExNWE5NmR8MTMzMTAxMjA0MHwxMzMxMDA0ODQwfDcyMDA=
   [i] decoded string > Ó{ßts­kgå×ÞéÇ{ï]ykÞ

The sad thing is the same functions are able to parse base64url encoded information retrieved from Facebook.

Functions

   sub timeoutStringGen{
    my ($name,$seconds) = @_;

    my $uuid    = uniqueID(); #generates random string
    my $timeStr = time();
    my $timeEnd = $timeStr + $seconds;

    my $timeoutString = "$uuid|$timeEnd|$timeStr|$seconds";

    my $encodedString = encode_base64url( $timeoutString );
    my $decodedString = decode_base64url( $timeoutString );

    _info "original string > $timeoutString"; #interal log function outputs to STDERR
    _info "encoded string > $encodedString";
    _info "decoded string > $decodedString";

    return $timeoutString;
  }


  sub timeoutStringParse{
    my ($timeoutString) = @_;
    return 0 unless $timeoutString;

    my ($uuid,$end,$start,$secs) = split /\Q|/,$timeoutString;

    my $curr  = time();
    my $left  = $end - $curr;

    my $isExpired = ($left > 0) ? 1 : 0;

    my $timeHash  = {
      uuid  => $uuid,
      end   => $end,
      start => $start,
      secs  => $secs,
      exp   => $isExpired,
      left  => $left,
      curr  => $curr
    };

    return $timeHash;

  }



but maybe you can help me understand why these dont work to encode and decode the string properly

          #--------

          sub encode64{
             my($data) = @_;
             return MIME::Base64::encode_base64($data);
          }

          #--------

          sub decode64{
             my($data) = @_;
             return MIME::Base64::decode_base64($data);
          }

          #--------

          sub encode_base64url{
             my($data) = @_;
             return 0 unless $data;
             $data = encode64($data);
             $data =~ tr#\-_#+/#;
             return($data);
          }

          #--------

          sub decode_base64url{
             my($data) = @_;
             return 0 unless $data;
             $data =~ tr#+/#\-_#;
             $data = decode64($data);
             return($data);
          }

Upvotes: 2

Views: 1337

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169494

This:

my $decodedString = decode_base64url( $timeoutString );

Should be:

my $decodedString = decode_base64url( $encodedString );
                                      ^^^^^^^^^^^^^^

As written you're decoding the original value, not the encoded one.

Upvotes: 4

Related Questions