How do I send POST data with LWP?

DisgruntledPerlLearner picture DisgruntledPerlLearner · Oct 1, 2010 · Viewed 62k times · Source

I want to make a program that communicates with http://www.md5crack.com/crackmd5.php. My goal is to send the site a hash (md5) and hopefully the site will be able to crack it. After, I would like to display the plaintext of the hash. My problem is sending the data to the site. I looked up articles about using LWP however I am still lost. Right now, the hash is not sending, some other junk data is. How would I go about sending a particular string of data to the site?

use HTTP::Request::Common qw(POST);  
use LWP::UserAgent; 


$ua = LWP::UserAgent->new();  
my $req = POST 'http://www.md5crack.com/crackmd5.php', [ 
 maxlength=> '2048',
 name=> 'term',
 size=>'55',
 title=>'md5 hash to crack',
 value=> '098f6bcd4621d373cade4e832627b4f6',
 name=>'crackbtn',
 type=>'submit',
 value=>'Crack that hash baby!',

]; 
$content = $ua->request($req)->as_string; 

print "Content-type: text/html\n\n"; 
print $content;

Answer

Alan Haggai Alavi picture Alan Haggai Alavi · Oct 1, 2010

You are POSTing the wrong data because you're taking the HTML to specify the widget and conflating it with the data it actually sends. The corrected data would be to just send the widget name and its value:

term: 098f6bcd4621d373cade4e832627b4f6

Instead, the data that is getting POSTed currently is:

maxlength: 2048
name:      term
size:      55
title:     md5 hash to crack
value:     098f6bcd4621d373cade4e832627b4f6
name:      crackbtn
type:      submit
value:     Crack that hash baby!

Corrected program:

use strict;
use warnings;

use LWP::UserAgent; 
use HTTP::Request::Common qw{ POST };
use CGI;

my $md5 = '098f6bcd4621d373cade4e832627b4f6';
my $url = 'http://www.md5crack.com/crackmd5.php';

my $ua      = LWP::UserAgent->new();
my $request = POST( $url, [ 'term' => $md5 ] );
my $content = $ua->request($request)->as_string();

my $cgi = CGI->new();
print $cgi->header(), $content;

You can also use LWP::UserAgent's post() method:

use strict;
use warnings;

use LWP::UserAgent;
use CGI;

my $md5 = '098f6bcd4621d373cade4e832627b4f6';
my $url = 'http://www.md5crack.com/crackmd5.php';

my $ua       = LWP::UserAgent->new();
my $response = $ua->post( $url, { 'term' => $md5 } );
my $content  = $response->decoded_content();

my $cgi = CGI->new();
print $cgi->header(), $content;

Always remember to use strict and use warnings. It is considered good practice and will save your time.