length of the data < length of the private key ..so i divided the message while taking it,put a ":::".then again encrpt it. look at the pgm to get an idea about this..
<?php
class cry
{
function gen_cert($userid)
{
$dn = array("countryName" => 'XX', "stateOrProvinceName" => 'State', "localityName" => 'SomewhereCity', "organizationName" =>'MySelf', "organizationalUnitName" => 'Whatever', "commonName" => 'mySelf', "emailAddress" => 'user@example.com');
$privkeypass = 'root';
$numberofdays = 365;
$privkey = openssl_pkey_new(array('private_key_bits' => 1024,'private_key_type' => OPENSSL_KEYTYPE_RSA));
$csr = openssl_csr_new($dn, $privkey);
$sscert = openssl_csr_sign($csr, null, $privkey, $numberofdays);
openssl_x509_export($sscert, $publickey);
openssl_pkey_export($privkey, $privatekey, $privkeypass);
openssl_csr_export($csr, $csrStr);
$fp=fopen("../PKI/private/$userid.key","w");
fwrite($fp,$privatekey);
fclose($fp);
$fp=fopen("../PKI/public/$userid.crt","w");
fwrite($fp,$publickey);
fclose($fp);
}
function encrypt($source,$rc)
{
$path="../PKI/public/server.crt";
$fp=fopen($path,"r");
$pub_key=fread($fp,8192);
fclose($fp);
openssl_get_publickey($pub_key);
$j=0;
$x=strlen($source)/10;
$y=floor($x);
for($i=0;$i<$y;$i++)
{
$crypttext='';
openssl_public_encrypt(substr($source,$j,10),$crypttext,$pub_key);$j=$j+10;
$crt.=$crypttext;
$crt.=":::";
}
if((strlen($source)%10)>0)
{
openssl_public_encrypt(substr($source,$j),$crypttext,$pub_key);
$crt.=$crypttext;
}
return($crt);
}
function decrypt($crypttext,$userid)
{
$passphrase="root";
$path="../PKI/private/server.key";
$fpp1=fopen($path,"r");
$priv_key=fread($fpp1,8192);
fclose($fpp1);
$res1= openssl_get_privatekey($priv_key,$passphrase);
$tt=explode(":::",$crypttext);
$cnt=count($tt);
$i=0;
while($i<$cnt)
{
openssl_private_decrypt($tt[$i],$str1,$res1);
$str.=$str1;
$i++;
}
return $str;
}
function sign($source,$rc)
{
$has=sha1($source);
$source.="::";
$source.=$has;
$path="../PKI/public/$rc.crt";
$fp=fopen($path,"r");
$pub_key=fread($fp,8192);
fclose($fp);
openssl_get_publickey($pub_key);
openssl_public_encrypt($source,$mese,$pub_key);
return $mese;
}
function verify($crypttext,$userid)
{
$passphrase="root";
$path="../PKI/private/$userid.key";
$fpp1=fopen($path,"r");
$priv_key=fread($fpp1,8192);
fclose($fpp1);
$res1= openssl_get_privatekey($priv_key,$passphrase);
openssl_private_decrypt($crypttext,$has1,$res1);
list($c1,$c2)=split("::",$has1);
$has=sha1($c1);
if($has==$c2)
{
$message=$c1;
return $message;
}
}
}
?>