php encrypts and decrypts instances using xor implementations

  • 2020-08-22 21:56:47
  • OfStack

If a = b ^ c; Then b=a ^ c (^ is the meaning of "xor"), when php is dealing with the characters of xor, it first converts the characters into the ascii value in base 2, and then converts the ascii value into the characters after obtaining the results. The principle says that it is too late to paste the code directly:


echo '<meta charset="utf-8">';
  $str=' Hello world ';  
  function jiami($str,$key){
   $key=md5($key);
   $k=md5(rand(0,100));// Equivalent to dynamic key 
   $k=substr($k,0,3);
   $tmp="";
   for($i=0;$i<strlen($str);$i++){
    $tmp.=substr($str,$i,1) ^ substr($key,$i,1);
   }
   return base64_encode($k.$tmp);
  }  
  function jiemi($str,$key){
   $len=strlen($str);
   $key=md5($key);
   $str=base64_decode($str);
   $str=substr($str,3,$len-3);
   $tmp="";
   for($i=0;$i<strlen($str);$i++){
    $tmp.=substr($str,$i,1) ^ substr($key,$i,1);
   }    
   return $tmp;
  }  
  $key='cc';
  $jh=jiami($str, $key);
  echo ' Encrypted before: '.$str.'<br>';
  echo ' After the encryption: '.$jh.'<br>';
  echo ' After decryption: '.jiemi($jh, $key).'<br>';

Under the opportunity to improve, this function is to achieve simple encryption and decryption


Related articles: