Alepri
Alepri

Reputation: 35

How to encode base64 md5 in CGI?

I need to post some form in CGI (Perl) and one of the inputs requires hash encoded in base64 md5. The sample provided by the side which should get, works in PHP as follows:

$hash = base64_encode(md5( $data1."|". $data2."|". $data3));

To make it work in CGI I’m using following code:

use Digest::MD5 qw( md5_base64 );
my $base64_digest = md5_base64($data1."|". $data2."|". $data3);

But encoded string on the outcome is different then if I do it in PHP. Looks like I’m doing it wrong in CGI. How to encode it correctly?


$ echo '<? echo base64_encode(md5("abc|def|ghi")), "\n"; ?>' | php
MzJjNDcyZmE0MjI3MWYyYWE0YTg1MWZkMmM1NzRkODc=

$ perl -MDigest::MD5=md5_base64 -E'say md5_base64("abc|def|ghi");'
MsRy+kInHyqkqFH9LFdNhw

Upvotes: 2

Views: 2090

Answers (1)

ikegami
ikegami

Reputation: 386551

Perl                             PHP
-------------------------------  ------------------------------ 
md5($string)                     md5($string, 1)
md5_hex($string)                 md5($string, 0)
md5_base64($string)              base64_encode(md5($string, 1))
encode_base64(md5_hex($string))  base64_encode(md5($string, 0))   WASTEFUL

PHP's md5 produces the hex of the hash, akin to D::MD5's md5_hex.

$ echo '<? echo md5("abc|def|ghi"), "\n"; ?>' | php
32c472fa42271f2aa4a851fd2c574d87

$ perl -E'
    use Digest::MD5 qw( md5_hex );
    say md5_hex("abc|def|ghi");'
32c472fa42271f2aa4a851fd2c574d87

base64 conveys the same information fewer characters.

$ echo '<? echo base64_encode(md5("abc|def|ghi", 1)), "\n"; ?>' | php
MsRy+kInHyqkqFH9LFdNhw==

$ perl -E'
   use Digest::MD5 qw( md5_base64 );
   say md5_base64("abc|def|ghi");'
MsRy+kInHyqkqFH9LFdNhw

$ perl -E'
   use Digest::MD5  qw( md5 );
   use MIME::Base64 qw( encode_base64 );
   say encode_base64(md5("abc|def|ghi"));'
MsRy+kInHyqkqFH9LFdNhw==

(Removing the trailing == doesn't change the value.)

What you are currently doing in PHP is very wasteful. It's both much longer than required, and requires extra CPU time to generate it.

$ echo '<? echo base64_encode(md5("abc|def|ghi")), "\n"; ?>' | php
MzJjNDcyZmE0MjI3MWYyYWE0YTg1MWZkMmM1NzRkODc=

$ perl -E'
   use Digest::MD5  qw( md5_hex );
   use MIME::Base64 qw( encode_base64 );
   say encode_base64(md5_hex("abc|def|ghi"), "");'
MzJjNDcyZmE0MjI3MWYyYWE0YTg1MWZkMmM1NzRkODc=

Upvotes: 3

Related Questions