Simples Two-Way PHP function to Encryption & Decryption String – without using openssl

The next php function will provide you a fast and very simple two-way system to encrypt a string or decrypt an encrypted string, useful for situations that do not require increased security, ie things that do not attract the attention of hackers or government spy services :).

function simpleStrCrypt($text, $userkey, $decode=false) {
  		
  $key = hash('sha256',$userkey,true); 
  $key_length = strlen($key)-1;	

  if ($decode) {
    $text = strtr($text, '-_', '+/');
    $text = base64_decode($text, false);
    $crc32 = ord($text[strlen($text) -1]);		
    $text_length = strlen($text)-1;
  } else {	
    $crc32 = crc32($text.$userkey) % 256;
    $text_length = strlen($text);
  }

  $k=0;	
  $code = '';

  for ($i = 0; $i < $text_length; $i++) {		
    $code .= chr( ord($text[$i]) ^ ord($key[$k]) ^ $crc32 );		
    if ($k < $key_length) 
      $k++;
    else 
      $k=0;
  }

  if ($decode === false) {
    $code .= chr($crc32);
    $code = base64_encode($code);
    if ($code === false)
      return false;		
    $code = strtr($code, '+/', '-_');		
  }
  
  return rtrim($code, '=');
}

* it can be used in GET / REQUEST parameters,  which you want to not be easy to read, such as an external link or other data without major importance:

http://localhost/test/exturl.php?url=TFNYXVRJCAJbUlEMERFOSERNQk9fR0pKWRZVV0FVFQ==

example of use:

<a target="_blank" rel="nofollow" href="exturl.php?url=<?php echo simpleStrCrypt('https://www.facebook.com/byrev', __EXT_URL_KEY); ?>" class="external-link"><i class="fa-facebook"></i></a>

example for decryption

$location = (!empty($_GET['url'])) ? simpleStrCrypt($_GET['url'], __EXT_URL_KEY, true) : '#';

the encryption key must be defined somewhere in the script:

define('__EXT_URL_KEY', 'd%wHXDxy9jz^K!FG');

Very important note:

This function is not recommended for protecting sensitive data because it does not have advanced encryption techniques but the simplest possible ones.

* It may be a bit slower than using openssl, but the resulting text is much shorter, which is preferable when encrypting links and we don’t want the result to be longer than 2000 characters !

byrev Written by:

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *