encryption/decryption question

Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.

Moderator: General Moderators

Post Reply
chopWood
Forum Commoner
Posts: 45
Joined: Fri Apr 30, 2010 9:28 am

encryption/decryption question

Post by chopWood »

The following code works well when used on a single php file. However when I use the code between two files (one on the client side one on the server side) the server doesn't seem to be able to decrypt the encrypted data that it received from the client. The server (which does not encrypt the results that it sends back to the client) returns the original encrypted data. It should have been decrypted and sent back as plain text.

So, why would it work in this example but not between a client and server script.


Code: Select all

<?PHP
 
$string = "one two three five";
$secret_key = "This is my sEcrEt key";
 $len= strlen($string);
// Encryption Algorithm
$etype = MCRYPT_RIJNDAEL_256;
 
// Create the initialization vector for added security.
$iv = mcrypt_create_iv(mcrypt_get_iv_size($etype, MCRYPT_MODE_ECB), MCRYPT_RAND);
 
// Output original string
PRINT "Original string: $string <p>";
 
// Encrypt $string
$encrypted_string = mcrypt_encrypt($etype, $secret_key, $string, MCRYPT_MODE_CBC, $iv);
 
// Convert to hexadecimal and send to browser
PRINT "Encrypted string: ".BIN2HEX($encrypted_string)."<p>";
$decrypted_string = mcrypt_decrypt($etype, $secret_key, $encrypted_string, MCRYPT_MODE_CBC, $iv);

$decrypted_string= substr($decrypted_string,0,$len);
PRINT "Decrypted string is: $decrypted_string <br/><br/>";

?>
THIS IS THE SERVER SCRIPT WHICH RECEIVES THE DATA. ITS FUNCTION IS TO TAKE ALL THE VOWELS OUT OF THE SENT STRING AND RETURN THE RESULT

Code: Select all

$secret_key = "This is my sEcrEt key";
$etype = MCRYPT_RIJNDAEL_256;
// Create the initialization vector for added security.
$iv = mcrypt_create_iv(mcrypt_get_iv_size($etype, MCRYPT_MODE_ECB), MCRYPT_RAND);
$input = file_get_contents("php://input");// encrypted string sent from client for vowel removal
// decrypt the input
$plainText= mcrypt_decrypt($etype, $secret_key, $input, MCRYPT_MODE_CBC, $iv);// decrypt it

$noVowels=deVowel($plainText); // remove the vowels
file_put_contents("php://output", $noVowels); //send it back

function deVowel($s) {
	trim ($s);
	$vowels= array("a","e","i","o","u");
	return str_replace($vowels,"",$s);
}


p.s. the php encoded has been enabled on the server and it does support the type being used.

thanks for any help
Post Reply