#!/usr/bin/perl
print "Content-type:text/html\n\n";

print <<EndOfHTML;
<html><head><title>SPCard Authentication Information</title></head>
<body background="a.jpg">
EndOfHTML

$ip=$ENV{'REMOTE_ADDR'};

read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
@ans = split(/&/, $buffer);
#ans will contain variable "custadd=somestring", "transno=439585"

($temp, $custadd) = split(/=/, $ans[0]);
($temp, $compadd) = split(/=/, $ans[1]);
($temp, $transno) = split(/=/, $ans[2]);
($temp, $amount) = split(/=/, $ans[3]);
($temp, $url) = split(/=/, $ans[4]);

$custadd =~ tr/+/ /;
$custadd =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$compadd =~ tr/+/ /;
$compadd =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$transno =~ tr/+/ /;
$transno =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$amount =~ tr/+/ /;
$amount =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$url =~ tr/+/ /;
$url =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;

srand (time ^ $$ ^ unpack "%32L*", `ps axww | gzip`); #a truely random seed unlike time
#challenge string generation
$challenge="";
for($i=0;$i<16;$i++)
{
 $temp=chr(rand(256));
 if(($temp eq "|") || ($temp eq "\n") || ($temp eq "\r")) { $temp="r";}
 $challenge=join("",("$temp",$challenge));
}

open(outf,">$ip.txt");
flock(outf,2);
print outf "$challenge|$custadd|$compadd|$transno|$amount\n";
close(outf);
system("./rsa S $ip.txt $ip.sign");

#temp 4 lines
#open(outf,">chall.txt");
#flock(outf,2);
#print outf "$challenge";
#close(outf);

print <<EndOfHTML;
<H2 ALIGN="CENTER"><BR>Welcome to Secure Payment Card</H2>
<H3 ALIGN="CENTER"><BR>Download
EndOfHTML
print "<a href=$ip.txt> file1</a> and <a href=$ip.sign> file2</a>";
print <<EndOfHTML;
  to be feeded to the software</H3>
<H3 ALIGN="CENTER"><FONT COLOR=RED>Important Note: Check all the information provided by the software<BR>Enter the authentication information only if all the information is correct.</FONT></H3>

<form action="process.cgi" method="POST">
<H4 ALIGN="CENTER">
<BR>Enter you SPCard ID and response to the challange to pay the bill<BR><BR>
ID: <input type="text" name="id"> <BR><BR>
Response: <input type="password" name="response"><BR><BR>
EndOfHTML

print "<input type=hidden name=\"custadd\" value=\"$custadd\">\n";
print "<input type=hidden name=\"compadd\" value=\"$compadd\">\n";
print "<input type=hidden name=\"transno\" value=\"$transno\">\n";
print "<input type=hidden name=\"amount\" value=$amount>\n";
print "<input type=hidden name=\"url\" value=$url>\n";

print <<EndOfHTML;
<input type="submit" value="Authenticate">
</H4>
</form>

</body>
</html>
EndOfHTML