Friday, December 14, 2007

Encrypting SOAP messages using PHP

If you have configured WSO2 WSF/PHP in your system, it takes only a few additional lines to get your SOAP messages encrypted.
Following is a PHP script, showing the necessary steps that you need to follow.
<?php
$reqPayloadString = <<<XML
<ns1:Privacy xmlns:ns1="http://privacy.abc.com/privacy"><Info>MyConfidentialInfo</Info></ns1:Privacy>
XML;

try {

/* 1. Load certificates*/
$rec_cert = ws_get_cert_from_file('your/path/to/certificate.cert');
$pvt_key = ws_get_key_from_file('your/path/to/private_key.pem');

/* 2. Create a new message request*/
$reqMessage = new WSMessage($reqPayloadString,
array("to"=>"http://privacy.abc.com/your/privacy_service.php",
"action" => "http://privacy.abc.com/privacy"));

/* 3. Create a security array to keep security properties*/
$sec_array = array("encrypt"=>TRUE,
"algorithmSuite" => "Basic256Rsa15",
"securityTokenReference" => "EmbeddedToken");

/* 4. Create a policy using the security array*/
$policy = new WSPolicy(array("security"=>$sec_array));

/* 5. Create a new security token*/
$sec_token = new WSSecurityToken(array("privateKey" => $pvt_key,
"receiverCertificate" => $rec_cert));

/* 6. Create a new web service client*/
$client = new WSClient(array("useWSA" => TRUE,
"policy" => $policy,
"securityToken" => $sec_token));
/* 7. Request*/
$resMessage = $client->request($reqMessage);

} catch (Exception $e) {
if ($e instanceof WSFault) {
printf("Soap Fault: %s\n", $e->Reason);
} else {
printf("Message = %s\n",$e->getMessage());
}
}
?>

A complete article on this can be found here...

No comments: