kvasilov48
10/20/2015 - 12:49 PM

Base64 Encode and Decode with Key

Base64 Encode and Decode with Key

<?php
$encrypted = encrypt("to encrypt string", "secret key");
echo $encrypted ;
$decrypted = decrypt($encrypted, "secret key");
 
echo $decrypted ;
 
function encrypt($string, $key) {
  $result = '';
  for($i=0; $i<strlen($string); $i++) {
    $char = substr($string, $i, 1);
    $keychar = substr($key, ($i % strlen($key))-1, 1);
    $char = chr(ord($char)+ord($keychar));
    $result.=$char;
  }
 
  return base64_encode($result);
}
 
function decrypt($string, $key) {
  $result = '';
  $string = base64_decode($string);
 
  for($i=0; $i<strlen($string); $i++) {
    $char = substr($string, $i, 1);
    $keychar = substr($key, ($i % strlen($key))-1, 1);
    $char = chr(ord($char)-ord($keychar));
    $result.=$char;
  }
 
  return $result;
}
 
?>