随机导致自定义加密/解密功能

时间:2012-09-19 16:46:44

标签: php encryption

我试图通过我创建的自定义函数加密数据...(基于base64) 代码可以工作但在某种程度上...它提供随机结果(有时是工作,有时不工作)。

<?php
set_time_limit(0);
class encryptor{
 function encrypt($data){
  $all = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!?@,.&*()$; ";
  $chars = str_split($all, 1); // Split $all to array of single characters
  $text_chars = str_split($data, 1); // Split $data to array of single characters

  // Create array of unique results based on the characters from $all
  foreach($chars as $char){
   $array[$char] = md5(uniqid(rand(), true));
  }
  // Replace the input text with the results from $array 
  foreach($text_chars as $text_char){
   $data = str_replace($text_char,$array[$text_char], $data);
  }
  // Encode and compress $array as $solution
  $solution = gzcompress(base64_encode(json_encode($array)),9);
  // Return the encoded solution + Breaker + encoded and compressed input text
  return $solution."BREAKHERE".gzcompress(base64_encode($data),9);
 }
 function decrypt($data){
  // Break the encrypted code to two parts
  $exploded = explode('BREAKHERE', $data);
  // Decoding the contents
  $contents = base64_decode(gzuncompress($exploded[1]));
  // Decoding solution ($array)
  $solves = json_decode(base64_decode(gzuncompress($exploded[0])),true);
  $fliped = array_flip($solves);
  // Replace the encrypted data with the solution
  foreach($solves as $solve){
   $contents = str_replace($solve,$fliped[$solve], $contents);
  }
  return($contents); // Return decoded data
  }
 }

$text = "11 1";
$enc = new encryptor();
$encrypted = $enc->encrypt($text);
$decrypted = $enc->decrypt($encrypted);
echo $decrypted;
?>

1 个答案:

答案 0 :(得分:1)

由于它只是为了好玩,这种变化似乎使其有效:

// Replace the input text with the results from $array
$encrypted = '';
foreach($text_chars as $text_char){
    //$data = str_replace($text_char,$array[$text_char], $data);
     $encrypted .= $array[$text_char];
}

在循环中运行str_replace会导致替换先前已替换过的数据。

除此之外,为了使加密数据的传输更容易,我改变了:

return $solution."BREAKHERE".gzcompress(base64_encode($data),9);

为:

return base64_encode($solution."BREAKHERE".gzcompress($data,9);

然后在解密器中进行适当的更改。压缩数据可以包含空字符和不可打印的字符,因此如果您对整个结果进行base64编码,则可以更轻松地传递它。