PHP string encryption

2 functions I wrote for securely encrypting strings between web pages using simple character level randomization.

The lock/encrypt function:
function djEncryptString($string, $key) 
{
	// $string is a random string to be encrypted.
	// $key is a randomized string that must contain all 
	// the characters found in $string as an absolute minimum.
	
	$key_chars = str_split($key);
	$string_chars = str_split($string);
	$key_coords = '';
	$key_coord_lengths = '';

	foreach($string_chars as $s_char) {
		for ($loop_a = 0; $loop_a < count($key_chars); $loop_a++) {
			if ($s_char == $key_chars[$loop_a]) {
				$key_coords .= (string)$loop_a;
				$key_coord_lengths .= (string)strlen($loop_a);
			}
		}
	}
	
	// Returns a string of coordinates of where the string 
	// characters are to be found within $key as well as the 
	// length of every coordinate since the string is a line 
	// of random numbers.
	
	return $key_coords .'-'. $key_coord_lengths;
}


The unlock/decrypt function:
function djDecryptString($enc_str, $key) 
{	
	// $enc_str is the output from djEncryptString().
	// $key is the same key as used to encrypt with.
	
	$key_chars = str_split($key);
	$enc_data = explode('-', $enc_str);
	$key_coords = $enc_data[0];
	$key_coord_lengths = str_split($enc_data[1]);
	
	$s = '';
	foreach ($key_coord_lengths as $c) {
		$s .= $key_chars[(int)substr($key_coords, 0, (int)$c)];
		$key_coords = substr($key_coords, (int)$c);
	}

	return $s;
}


PHP example usage:
// Create a random key to be used by both functions.
$key = str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890. ');

$original_string = 'This is a random string.';
$encrypted_string = djEncryptString($original_string, $key);

echo 'Key used: '. $key .'<br><br>';
echo 'Original string: '. $original_string .'<br><br>';
echo 'Encrypted string: '. $encrypted_string .'<br><br>';
echo 'Decrypted string: '. djDecryptString($encrypted_string, $key);


The above testing code produces output similar to this:
Key used: L2RZ6oMfcCjpWIuPxKsT5rSzteq.Dmln0O17d8YUX FgV4yNBiEvbJH3Q9AakhwG

Original string: This is a random string.

Encrypted string: 19614918414918415941215931365294118242149314327-222222222222221222222222

Decrypted string: This is a random string.


Demo

This way of encrypting a string between web pages is very secure if you keep the key secret. If you keep the contents of $key to a minimum of all alphanumeric characters (a-z, A-Z, 0-9) plus any special characters your $string may have, then just encrypting "Hi!" will have 633 = 250047 combinations. If putting an additional layer of security on top, it will be even better. I suggest limiting the amount of allowed failed tries for any authorization system, or at least make it troublesome to attack it with brute force.

This document was last updated July 6th, 2011.
Written by: Dag Jonny Nedrelid
©2007-2012 http://thronic.com


Feel free to leave a comment.
Name:
URL:
0