String encryption in PHP

String encryption in PHP

How does it work?
A key is generated on the first page that also encrypts the string (or code if you want). The same key is used on the second page to decrypt it. Consider the functions below for more information. On the bottom you’ll find a test script to see the effect of the functions.

Generating a random string value in PHP (e.g a Captcha code):

function CreateRandomStringPHP() {
  $code = substr(str_shuffle('abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'),0,5);
  return $code;
}

If you are using another language, consider using a function like this:

function CreateRandomString() {
  $Characters = array(
  'a','b','c','d','e','f','g','h','i','j','k','m','n','p','q','r','s','t','u','v','w','x','y','z',
  'A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z',
  '2','3','4','5','6','7','8','9');

  $Code = '';
  for( $loop_b = 1; $loop_b <= 5; $loop_b++ ) {
    $Code .= $Characters[mt_rand(0,count($Characters)-1)];
  }

  return $Code;
}

Both of the above functions will generate a 5-length value. This will provide one value out of 550731776 possible combinations which should be enough for most needs.

The lock (or encrypt) function:

/*
  str LockCode(str $code, str $key)

  A codelock function (or encryption if you want).
  I wrote because I wanted a nice solution for keeping codes
  such as Captcha codes safe and secure for transferring between
  sites.

  It takes a $code of random length and locking $key as parameters.
  You'll need to use the same key to unlock it.

  The value this function returns, is simply a set of location
  coordinates in the key where the characters of the $code is found.
  This is again merged together with the lengths of every coordinate,
  since every coordinate can be 1 or 2 in length as long as the $key
  is under 100 characters in length (0-99).

  In the end, it should provide a safely locked $code, based on that
  you keep the $key hidden. Do NOT show it in your HTML. The key
  used in this example, with 56 alphanumeric characters where I have
  stripped out the following chars: 1, I, l, o, O and 0 (they are
  unpractical) has 7,9164324866862966607842406018063e+97
  combinations. This should be enough to keep the $code safe...
*/
function LockCode($code,$key) {
  $key_chars = str_split($key);
  $code_chars = str_split($code);
  $LockedKeyCoords = '';
  $LockedCoordLengths = '';

  foreach($code_chars as $c_char) {
    for($loop_a=0; $loop_a<count($key_chars); $loop_a++) {
      if($c_char==$key_chars[$loop_a]) {
        $LockedKeyCoords .= (string)$loop_a;
        $LockedCoordLengths .= (string)strlen($loop_a);
      }
    }
  }

  return $LockedKeyCoords . $LockedCoordLengths;
}

The unlock (or decrypt) function:

/*
  str UnlockCode(str $coords, str $key, int $keylength)

  The unlock function introduces a new parameter: $Keylength.
  This defines how many characters your $code was before you locked it.
*/
function UnlockCode($coords,$key,$keylength) {
  $key_chars = str_split($key);
  $keylengths = str_split(substr($coords,-$keylength));
  $UnlockedCode = '';

  foreach($keylengths as $length) {
    $UnlockedCode .= $key_chars[(int)substr($coords,0,(int)$length)];
    $coords = substr($coords,(int)$length);
  }

  return $UnlockedCode;
}

PHP code to test with:

/*
  The $Key MUST contain the characters you use to create the
  code with. Using the same string as you did to make the $Code
  with is a good choice. Generate a key on a standalone page,
  then use the same key on the page that locks the string, and
  on the page that unlocks the string.

  If you want a new random key every time you use the locking
  functions, you'll have to use a database system to store and
  retrieve them. And use sessions for identifying the keys. This
  would make a separate article, so I won't explain how to do it
  here.
*/
$Key = str_shuffle('abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789');

// Test it out.
$Code = CreateRandomStringPHP();
$LockedCode = LockCode($Code,$Key);
echo 'Key used: '. $Key .'<br><br>';
echo 'New code: '. $Code .'<br>';
echo 'Locked code: '. $LockedCode .'<br>';
echo 'Unlocked code: '. UnlockCode($LockedCode,$Key,5) .'<br><br>';
echo 'Reload this page to generate new results.';

The above testing code would produce something like this:

Key used: F7AYMQTscfHEPvSBXw5C3eWhj6kUxbn2ayrtGzNiqDV4m9ugJLKZpR8d

New code: c42yV
Locked code: 84331334212222
Unlocked code: c42yV

You can try it out yourself here (opens in a new window).

Leave a Reply